vue.js 2如何从vuex监视存储值 [英] vue.js 2 how to watch store values from vuex

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

问题描述

我正在同时使用vuexvuejs 2.

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

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

我想在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;
  },
};

我想知道my_state

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

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

推荐答案

例如,假设您有一篮子水果, 每次您在篮子中添加或删除水果时, 想要(1)显示有关水果计数的信息,但是,您还(2)想以某种幻想的方式通知水果的数量...

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, but you also (2) want to be notified of the count of the fruits in some fancy fashion...

fruit-count-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>

请注意,watch对象中的功能名称必须与computed对象中的功能名称匹配.在上面的示例中,名称为count.

Please note, that the name of the function in the watch object, must match the name of the function in the computed object. In the example above the name is count.

watched属性的新旧值将作为参数传递到watch回调(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

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:

  • Computed properties and watchers
  • API docs: computed
  • API docs: watch

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

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