vuex 监听状态改变

首先配置store/index.js

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);//记得这一步

export default new vuex.Store({
	state: {
		name: '',
		curtId: 0
	},
	getters: {//如果要使用watch观察状态改变那么一定配置这一项

	},
	mutations: {//需要执行多个state 的操作 , 使用 mutations 会来触发会比较好维护
		valIsChange(state, newVal){
			state.name = newVal.name
		},
		idChange(state){
			state.curtId++
		}
	},
	actions: {//需要执行多个 mutations 就需要用 action 了
		//changesVal(context, newVal){
			// console.log('actionsNewVal:', newVal.kk)
			//context.commit('valIsChange',{name: newVal.kk});
		//},
                changesVal({commit},newVal){//跟上面写法一样,可以简化代码
                    commit('valIsChange',{name: newVal.kk})
                },
		changeId({commit}){
			commit('idChange')
		}
	}
})

main.js引用

import store from './store'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

在需要监听状态改变的页面使用computed 和 watch实现监听

<template>
    <div>
        <div @click='changeName'>测试mutations</div>
        <div @click='changeName2'>测试actions</div>
        <div @click="changeId">当前值点击 +1:{{this.$store.state.curtId}}</div>
    </div>
</template>


<script>
    import {mapState, mapActions} from 'vuex'
    export default {
            data() {
               return {
                   now: 0//
               }
           },
           computed: {
              //name() {
               // return this.$store.state.name;
              //}
               ...mapState({//等价于上面的写法
                    name: state=>state.name
                })
            },
            watch: {//监听值改变
              name(newVal, oldVal) {
                console.log('改变值:', newVal, '旧值:', oldVal)
              }
            },
           methods: {
            // changeId(){
              //   this.$store.dispatch('changeId')
              // },
              ...mapActions([//跟上面写法实现一样,可以简化代码
                "changeId"
              ]),
              changeName(){//要传值可以用下面这种写法,如果只触发方法就用上面的简写
                this.now++
                this.$store.commit('valIsChange', {name: ('wangtao'+this.now)})
              },
              changeName2(){
                this.$store.dispatch('changesVal', {name: 'xxxxxx'})
              }
           }
    }
</script>

要点:
1.一定要配置store/index.js 里面的getters,空的也行
2.改变state值建议用this.$store.commit('valIsChange', {name: ('wangtao'+this.now)}),第一个参数为 mutations里面定义的方法名,想监听谁就填谁名字,第二个参数是传值

原文地址:https://www.cnblogs.com/yzyh/p/10193281.html