Vue.js中离开视频页面时清除localStorage视频src值的问题
Got it, let's work through this problem step by step! The core issue here is that you're trying to clear the localStorage value at the wrong lifecycle stage, and you need to sync that action with Vuex properly.
Why Your Current Approach Isn't Working
Running the cleanup in the mounted hook only triggers when the component first loads—this doesn't do anything when you leave the page. You need to trigger the clear operation right before the component is destroyed or you navigate away from the page.
Step 1: Update Your Vuex Mutation to Sync State and LocalStorage
First, make sure your mutation handles both updating the Vuex state and removing the corresponding localStorage entry. This keeps your state consistent:
// In your Vuex store module (e.g., store/modules/videos.js) const mutations = { // Existing mutations... CLEAR_WATCHED_VIDEO_SRC(state) { // Clear the relevant state in Vuex state.watchedVideoSrc = null; // Adjust this to match your actual state key // Remove the item from localStorage localStorage.removeItem('watchedVideoSrc'); // Match your localStorage key } }; // If you prefer using actions (for async logic, though this is sync) const actions = { clearWatchedVideo({ commit }) { commit('CLEAR_WATCHED_VIDEO_SRC'); } };
Step 2: Trigger the Cleanup at the Right Lifecycle Hook
Use the appropriate lifecycle hook to trigger the mutation when you leave the page. Here's how to do it for both Vue 2 and Vue 3:
For Vue 3 (Composition API)
Use onBeforeUnmount to run cleanup right before the component is unmounted:
<template> <!-- Your video player template --> </template> <script setup> import { useStore } from 'vuex'; import { onBeforeUnmount } from 'vue'; const store = useStore(); // Run cleanup when leaving the page onBeforeUnmount(() => { store.commit('videos/CLEAR_WATCHED_VIDEO_SRC'); // Or use an action if you set one up: store.dispatch('videos/clearWatchedVideo'); }); </script>
For Vue 2 (Options API)
Use beforeDestroy (or beforeRouteLeave if using Vue Router for navigation guards):
<template> <!-- Your video player template --> </template> <script> export default { mounted() { // Your existing initialization logic }, // Option 1: Trigger on component destroy beforeDestroy() { this.$store.commit('videos/CLEAR_WATCHED_VIDEO_SRC'); }, // Option 2: Trigger when navigating away (if using Vue Router) beforeRouteLeave(to, from, next) { this.$store.commit('videos/CLEAR_WATCHED_VIDEO_SRC'); next(); // Don't forget to call next() to proceed with navigation } }; </script>
Key Notes
- Always make sure your Vuex state and localStorage stay in sync—don't modify localStorage directly outside of Vuex mutations/actions unless you have a good reason.
- Double-check that your mutation targets the correct state key and localStorage key (matching what you use to save the video src initially).
内容的提问来源于stack exchange,提问作者Chris Michael

