vue.js 2如何从vuex看存储值

JavaScript

猿小宇宙小哥

2020-03-09

我使用vuexvuejs 2在一起。

我是新手vuex,我想观看store变量更改。

我想watch在我功能添加vue component

这是我到目前为止所拥有的:

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

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

我想知道是否有任何变化 my_state

如何store.my_state在vuejs组件中观看

第363篇《vue.js 2如何从vuex看存储值》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
小小卡卡西小卤蛋 2020.03.09

如上所述,直接在商店中查看更改不是一个好主意

但在某些非常罕见的情况下,它可能对某人有用,所以我将保留此答案。对于其他情况,请参阅@ gabriel-robert答案

您可以通过执行此操作state.$watch将此添加到组件中的created(或需要在其中执行的)方法中

this.$store.watch(
    function (state) {
        return state.my_state;
    },
    function () {
        //do something on data change
    },
    {
        deep: true //add this if u need to watch object properties change etc.
    }
);

更多详细信息:https : //vuex.vuejs.org/api/#watch

L十三 2020.03.09

您还可以订阅商店突变:

store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})

https://vuex.vuejs.org/api/#subscribe

神奇老丝 2020.03.09

如果您使用 TypeScript,则可以:

import { Watch } from "vue-property-decorator";

..

@Watch("$store.state.something")
private watchSomething() {
   // use this.$store.state.something for access
   ...
}

达蒙Davaid斯丁 2020.03.09

mapGetters正如Gabriel所说,观察商店变化的最好方法是使用但是在mapGetters某些情况下,您可能无法通过参数来做到这一点,例如,您想使用参数从商店中获取一些东西:

getters: {
  getTodoById: (state, getters) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

在这种情况下,您将无法使用mapGetters您可以尝试执行以下操作:

computed: {
    todoById() {
        return this.$store.getters.getTodoById(this.id)
    }
}

但不幸的todoById 是,只有this.id更改后才会更新

如果您希望在这种情况下更新组件,请使用this.$store.watch Gong提供的解决方案或自觉处理组件并this.id在需要更新时进行更新todoById

Itachi猪猪Green 2020.03.09

我认为提问者想与Vuex一起使用手表。

this.$store.watch(
      (state)=>{
        return this.$store.getters.your_getter
      },
      (val)=>{
       //something changed do something

      },
      {
        deep:true
      }
      );

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android