Javascript vue.js 2 如何从 vuex 中观察存储值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43270159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:47:56  来源:igfitidea点击:

vue.js 2 how to watch store values from vuex

javascriptvue.jsvuejs2vuex

提问by raffffffff

I am using vuexand vuejs 2together.

我正在使用vuexvuejs 2一起。

I am new to vuex, I want to watch a storevariable change.

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

I want to add the watchfunction in my vue component

我想watch在我的vue component

This is what I have so far:

这是我到目前为止:

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

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

I want to know if there are any changes in the my_state

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

How do I watch store.my_statein my vuejs component?

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

回答by Anastazy

Let's say, for example, that you have a basket of fruits, and each time you add or remove a fruit from the basket, you want to (1) display info about fruit count, butyou also (2) want to be notified of the count of the fruits in some fancy fashion...

例如,假设您有一篮子水果,每次从篮子中添加或移除水果时,您希望 (1) 显示有关水果数量的信息,您还希望 (2) 收到通知以某种花哨的方式计算水果的数量......

fruit-count-component.vue

水果计数component.vue

<template>
  <!-- We meet our first objective (1) by simply -->
  <!-- binding to the count property. -->
  <p>Fruits: {{ count }}</p>
</template>

<script>
import basket from '../resources/fruit-basket'

export default () {
  computed: {
    count () {
      return basket.state.fruits.length
      // Or return basket.getters.fruitsCount
      // (depends on your design decisions).
    }
  },
  watch: {
    count (newCount, oldCount) {
      // Our fancy notification (2).
      console.log(`We have ${newCount} fruits now, yay!`)
    }
  }
}
</script>

Please note, that the name of the function in the watchobject, must match the name of the function in the computedobject. In the example above the name is count.

请注意,watch对象中的函数名称必须与对象中的函数名称匹配computed。在上面的例子中,名称是count.

New and old values of a watched property will be passed into watch callback (the count function) as parameters.

监视属性的新旧值将作为参数传递给监视回调(计数函数)。

The basket store could look like this:

篮子商店可能看起来像这样:

fruit-basket.js

水果篮.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const basket = new Vuex.Store({
  state: {
    fruits: []
  },
  getters: {
    fruitsCount (state) {
      return state.fruits.length
    }
  }
  // Obviously you would need some mutations and actions,
  // but to make example cleaner I'll skip this part.
})

export default basket

You can read more in the following resources:

您可以在以下资源中阅读更多内容:

回答by Gabriel Robert

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.

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

import { mapGetters } from 'vuex'

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

In your store:

在您的商店:

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

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

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

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

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

回答by GONG

As mentioned above it is not good idea to watch changes directly in store

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

But in some very rare cases it may be useful for someone, so i will leave this answer. For others cases, please see @gabriel-robert answer

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

You can do this through state.$watch. Add this in your created(or where u need this to be executed) method in component

您可以通过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.
    }
);

More details: https://vuex.vuejs.org/api/#watch

更多详情:https: //vuex.vuejs.org/api/#watch

回答by micah5

It's as simple as:

这很简单:

watch: {
  '$store.state.drawer': function() {
    console.log(this.$store.state.drawer)
  }
}

回答by yeahdixon

I think the asker wants to use watch with Vuex.

我认为提问者想将 watch 与 Vuex 一起使用。

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

      },
      {
        deep:true
      }
      );

回答by dube

This is for all the people that cannot solve their problem with getters and actually really need a watcher, e.g. to talk to non-vue third party stuff (see Vue Watcherson when to use watchers).

这适用于所有无法使用 getter 解决他们的问题并且实际上确实需要观察者的人,例如与非 vue 第三方内容交谈(请参阅Vue Watchers了解何时使用观察者)。

Vue component's watchers and computed values both also work on computed values. So it's no different with vuex:

Vue 组件的观察者和计算值也适用于计算值。所以它与 vuex 没有什么不同:

import { mapState } from 'vuex';

export default {
    computed: {
        ...mapState(['somestate']),
        someComputedLocalState() {
            // is triggered whenever the store state changes
            return this.somestate + ' works too';
        }
    },
    watch: {
        somestate(val, oldVal) {
            // is triggered whenever the store state changes
            console.log('do stuff', val, oldVal);
        }
    }
}

if it's only about combining local and global state, the mapState's docalso provides an example:

如果只是关于结合本地和全局状态,mapState 的文档还提供了一个示例:

computed: {
    ...mapState({
        // to access local state with `this`, a normal function must be used
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
    }
})

回答by Zhang Sol

if you use typescript then you can :

如果您使用打字稿,那么您可以:

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

..

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

回答by Mukundhan

Create a Local stateof your store variable by watching and setting on value changes. Such that the local variable changes for form-input v-modeldoes not directly mutate the store variable.

通过观察和设置值变化来创建商店变量的本地状态。这样,表单输入 v-model的局部变量更改不会直接改变store 变量

data() {
  return {
    localState: null
  };
 },
 computed: {
  ...mapGetters({
    computedGlobalStateVariable: 'state/globalStateVariable'
  })
 },
 watch: {
  computedGlobalStateVariable: 'setLocalState'
 },
 methods: {
  setLocalState(value) {
   this.localState = Object.assign({}, value);
  }
 }

回答by Arseniy-II

The best way to watch store changes is to use mapGettersas Gabriel said. But there is a case when you can't do it through mapGetterse.g. you want to get something from store using parameter:

观察商店变化的最好方法是使用mapGettersGabriel 所说的。但是有一种情况,你不能通过mapGetters例如你想使用参数从商店获取一些东西:

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

in that case you can't use mapGetters. You may try to do something like this instead:

在这种情况下,您不能使用mapGetters. 你可以尝试做这样的事情:

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

But unfortunately todoByIdwill be updated only if this.idis changed

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

If you want you component update in such case use this.$store.watchsolution provided by Gong. Or handle your component consciously and update this.idwhen you need to update todoById.

如果您希望在这种情况下更新组件,请使用this.$store.watch龚提供的解决方案。或者有意识地处理你的组件并this.id在需要更新时更新todoById

回答by Jakub A Suplicki

If you simply want to watcha state propertyand then act within the component accordingly to the changes of that property then see the example below.

如果你只想一个国家的财产,然后将组件内采取相应的行动,以该财产的变化,然后看下面的例子。

In store.js:

store.js

export const state = () => ({
 isClosed: false
})
export const mutations = {
 closeWindow(state, payload) {
  state.isClosed = payload
 }
}

In this scenario, I am creating a booleanstate property that I am going to change in different places in the application like so:

在这种情况下,我将创建一个boolean状态属性,我将在应用程序的不同位置对其进行更改,如下所示:

this.$store.commit('closeWindow', true)

Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mountedhook:

现在,如果我需要在其他组件中查看该状态属性,然后更改本地属性,我会在mounted钩子中写入以下内容:

mounted() {
 this.$store.watch(
  state => state.isClosed,
  (value) => {
   if (value) { this.localProperty = 'edit' }
  }
 )
}

Firstly, I am setting a watcher on the state property and then in the callback function I use the valueof that property to change the localProperty.

首先,我在 state 属性上设置了一个观察者,然后在回调函数中我使用该value属性的 来更改localProperty.

I hope it helps!

我希望它有帮助!