问题描述
我一起使用 vuex
和 vuejs 2
。
我是 vuex
的新手,我想看一个商店
变量。
I am new to vuex
, I want to watch a store
variable change.
我想在我的 vue组件中添加
watch
函数
I want to add the watch
function in my 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 $是否有任何变化c $ c>
如何在我的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, youwant 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, yaay!`)
}
}
}
</script>
请注意,手表中的功能名称
object,必须与 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
.
观看的属性的新旧值将传递给监视回调(计数函数)作为参数。
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
}
}
// Obvously 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
这篇关于vuejs 2如何从vuex中观察商店价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!