vuex 監聽狀態改變
阿新 • • 發佈:2018-12-28
首先配置store/index.js
import Vue from 'vue' import vuex from 'vuex' Vue.use(vuex);//記得這一步 export default new vuex.Store({ state: { name: '', curtId: {} }, getters: {//如果要使用watch觀察狀態改變那麼一定配置這一項 }, mutations: { valIsChange(state, newVal){ state.name = newVal.name } } })
main.js引用
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
在需要監聽狀態改變的頁面使用computed 和 watch實現監聽
<template> <div @click='changeName'>改變state.name值,動態監聽狀態變化</div> </template> <script> export default { data() { return { now: 0// } }, computed: { name() { return this.$store.state.name; } }, watch: {//監聽值改變 name(newVal, oldVal) { console.log('改變值:', newVal) } }, methods: { changeName(){ this.now++ this.$store.commit('valIsChange', {name: ('wangtao'+this.now)}) } } } </script>
要點:
1.一定要配置store/index.js 裡面的getters,空的也行
2.改變state值建議用this.$store.commit('valIsChange', {name: ('wangtao'+this.now)}),第一個引數為 mutations裡面定義的方法名,想監聽誰就填誰名字,第二個引數是傳值