vuex 监听状态改变

首先配置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里面定义的方法名,想监听谁就填谁名字,第二个参数是传值

猜你喜欢

转载自www.cnblogs.com/yzyh/p/10193281.html
今日推荐