代码之家  ›  专栏  ›  技术社区  ›  user7693832

为什么我提交将状态的数据设置为null,组件状态不更改,直到我刷新页面?

  •  0
  • user7693832  · 技术社区  · 8 年前

    在我的 store.js :

      state: {
      ...
    
      user_info: LocalStorageUtil.get('user_info')
      },
    
      mutations: {
        set_user_info_null(state){
          state.user_info = null
        }
      }
    

    在我的组件中:

        // in the template
        <div v-if="user_info" class="welcome">
              <a @click="welcome_username">欢迎您,{{user_info.username}}!</a>/<a @click="logout">退出</a>
        </div>
    
    // in the script
    data(){
      return {
        user_info: this.$store.state.user_info,
        ...
    
      }
    
    methods: {
      ...
    
      ... // in the logout method
      LocalStorageUtil.clear('user_info')
      this.$store.commit('set_user_info_null')  // store set to null
    

    你看,我清除了 user_info 首先,然后Vuex提交 set_user_info_null . Vuex的状态user\u info将设置为 null

    enter image description here

    但是,在组件的数据中,user\u info仍然是对象:

    enter image description here


    编辑-1

    如果我使用代码:

    import { mapState } from "vuex";
    export default {
      computed: {
        ...mapState("user_info")
      }
    };
    

    我出错了:

    TypeError:undefined不是对象(正在计算“object.keys(map)”)

    在此行中:

    computed: {
      ...mapState("user_info")
    },
    components: {   // in this line
    ...
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Jacob Goh    8 年前

    此部件在您的组件中有问题

    data(){
      return {
        user_info: this.$store.state.user_info,
        ...
    
      }
    

    您正在声明与Vuex存储区分离的本地组件状态。更新Vuex存储时,这不会改变。

    正确的方法是使用 mapState

    import { mapState } from "vuex";
    export default {
      computed: {
        ...mapState(["user_info"])
      }
    };
    

    就好像你是路过 user_info 作为 prop 到该组件。更新Vuex存储时,此组件也将更新。

        2
  •  0
  •   aircraft    8 年前

    在较新(高于v.2.3.4)版本Vue中。如果代码中有 this.user_info=xxx :

    您可以检查 source code

    因此,首先我建议您更改 this.$store.state.user_info=xxx 替换的 这用户信息=xxx

    其次,你应该看看 Two-way Computed Property

    computed: {
      message: {
        get () {
          return this.$store.state.user_info
        },
        set (value) {
          this.$store.commit('set_user_info_null')
        }
      }
    }
    
    推荐文章