Vuex状态变更时通过计算属性更新组件:收藏按钮文本切换及刷新问题
Hey Anna, let's sort out this button text problem in your movie app. The core issue here is that Vuex stores state in memory by default—so when you refresh the page, your saved favorites list disappears, making your computed property think the movie isn't favorited anymore. Here's how to fix this properly:
1. Persist Vuex Favorites to LocalStorage
First, we need to save your favorites list to the browser's localStorage so it survives page reloads. We'll sync this with your Vuex store:
Update Your Vuex Store
const store = new Vuex.Store({ state: { // Initialize favorites from localStorage if it exists favorites: JSON.parse(localStorage.getItem('movieFavorites')) || [] }, mutations: { ADD_FAVORITE(state, movie) { state.favorites.push(movie); // Save to localStorage after updating localStorage.setItem('movieFavorites', JSON.stringify(state.favorites)); }, REMOVE_FAVORITE(state, movieId) { state.favorites = state.favorites.filter(movie => movie.id !== movieId); // Update localStorage after removing localStorage.setItem('movieFavorites', JSON.stringify(state.favorites)); } }, actions: { addFavorite({ commit }, movie) { commit('ADD_FAVORITE', movie); }, removeFavorite({ commit }, movieId) { commit('REMOVE_FAVORITE', movieId); } }, getters: { isFavorite: (state) => (movieId) => { // Helper getter to check if a movie is in favorites return state.favorites.some(movie => movie.id === movieId); } } });
2. Refine Your Component's Button Logic
Use the Vuex getter to cleanly check if the movie is favorited, and bind the button text and click handler accordingly:
In Your Movie Component
<template> <button @click="toggleFavorite"> {{ isMovieFavorite ? 'Remove from favourites' : 'Add to favourites' }} </button> </template> <script> import { mapGetters, mapActions } from 'vuex'; export default { props: ['movie'], computed: { ...mapGetters(['isFavorite']), isMovieFavorite() { // Use the getter to check current movie's status return this.isFavorite(this.movie.id); } }, methods: { ...mapActions(['addFavorite', 'removeFavorite']), toggleFavorite() { if (this.isMovieFavorite) { this.removeFavorite(this.movie.id); } else { this.addFavorite(this.movie); } } } }; </script>
3. Why This Works
- LocalStorage Persistence: By writing the favorites list to
localStorageevery time it changes, and loading it back when the store initializes, your favorites stay intact across page reloads. - Getter for Reusability: The
isFavoritegetter centralizes the logic for checking if a movie is favorited, making your component code cleaner and less error-prone. - Toggle Handler: The
toggleFavoritemethod handles both adding and removing, ensuring the button text updates correctly immediately after the action is dispatched.
Give this a try—your button text should now stay consistent even after refreshing the page!
内容的提问来源于stack exchange,提问作者Anna Collins

