You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuex状态变更时通过计算属性更新组件:收藏按钮文本切换及刷新问题

Fixing Vuex Button Text Issue After Page Refresh

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 localStorage every time it changes, and loading it back when the store initializes, your favorites stay intact across page reloads.
  • Getter for Reusability: The isFavorite getter centralizes the logic for checking if a movie is favorited, making your component code cleaner and less error-prone.
  • Toggle Handler: The toggleFavorite method 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:10:34