如何从 vuex 中查看存储值? [英] How to watch store values from vuex?

查看:272
本文介绍了如何从 vuex 中查看存储值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我同时使用 vuexvuejs 2.

我是 vuex 的新手,我想观察 store 变量的变化.

I am new to vuex, I want to watch a store variable change.

我想在我的vue组件

这是我目前所拥有的:

import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};

我想知道my_state

如何在我的 vuejs 组件中查看 store.my_state?

How do I watch store.my_state in my vuejs component?

推荐答案

你不应该使用组件的观察者来监听状态变化.我建议您使用 getter 函数,然后将它们映射到您的组件中.

You should not use component's watchers to listen to state change. I recommend you to use getters functions and then map them inside your component.

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters({
      myState: 'getMyState'
    })
  }
}

在您的商店中:

const getters = {
  getMyState: state => state.my_state
}

您应该能够通过在组件中使用 this.myState 来监听对商店所做的任何更改.

You should be able to listen to any changes made to your store by using this.myState in your component.

https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper

这篇关于如何从 vuex 中查看存储值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆