vuex的使用

需求:a.vue点击事件,触发b.vue页面的事件

vuex全局状态管理,可以存储全局数据,实现组件间、页面间的通信,简单的项目可以用vue-bus(想了解的同学我之前的博客有记录过vue-bus的使用),中大型复杂项目建议使用vuex,vuex的具体细节就不赘述了,文档很多,我做个简单的介绍和具体使用方法。

vuex文档:

https://vuex.vuejs.org/zh/guide/state.html

发现一篇比较详细的讲解,可以参考一下:

https://segmentfault.com/a/1190000011914191

1.先安装vuex

npm install vuex --save

2.项目src下新建store目录和store.js文件

通常设计store对象都包含4个属性:state,getters,actions,mutations

每一个 Vuex 应用的核心就是 store(仓库),store 基本上就是一个容器,它包含着应用中大部分的状态(state) Vuex 和单纯的全局对象有以下不同:

1.Vuex的状态储存是响应式的,当 Vue 组件从 store 中读取状态时,若store中的状态发生变化,那么相应的组件也会得到高效更新

2.不能直接改变 store 中的状态,改变 store 中状态的唯一途径就是显式的提交(commit)mutation 这样可以更方便的跟踪状态的变化

 store.js:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    deviceAdd: false
  },
  mutations: {
    closeDeviceAdd (state) {
      state.deviceAdd = true
    }
  },
  actions: {
    actionCloseDeviceAdd ({commit}) {
      commit('closeDeviceAdd')
    }
  }
})
export default store

main.js中引入:

import Vuex from 'vuex';
import store from './store/store.js'

Vue.use(Vuex)

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');

3.a.vue触发:

this.$store.dispatch('actionCloseDeviceAdd')

4.b.vue监听触发事件:

computed: {
    deviceAdd () {
         return this.$store.state.deviceAdd
    }
},
watch: { // 监听store中变量值的改变
     deviceAdd: function (newVal, oldVal) {
         ...do something // 自定义事件
      }
}

 vuex的功能强大,使用程度不仅仅于此,本篇博文简略介绍,希望对你有所帮助!

原文地址:https://www.cnblogs.com/wangqiao170/p/9337543.html