父子组件通信是传递私有数据,非父子组件通信传递的是共享数据,对共享数据进行管理可以帮助我们对全局状态进行统一管理
vuex 安装
npm install vuex --save
vuex 挂载
import Vuex from ‘vuex‘Vue.use(Vuex)
store 创建
var store = new Vuex.Store( ???state : { ???????count : 0 ???}, ???mutations:{ ???????})
加载到 vue 实例
new Vue({ ???el : ‘#app‘, ???router, ???components : { ???????App ???}, ???template : ‘<App/>‘, ???store})
访问 store 数据
<span>组件1:</span><input type=‘text‘ v-model=‘$store.state.count‘>
改变 store 数据
直接操作 $store.state.count 是不被推荐的,store 提供了一个操作 count 值的接口 motations
// 仓库中定义方法,方法的第一个参数永远是state,类似过滤器var store = new Vuex.Store({ ?state: { ???count: 0 ?}, ?mutations: { ???add(state) { ?????state.count++ ???} ?}})
// 组件通过commit方法进行调用export default { ?methods: { ???add() { ?????this.$store.commit("add"); ???} ?}};
调用接口并传参
commit 方法可以使组件改变共享数据,同时也可以传入参数,但是限制只能传入一个自己自定义的参数,所以在传入参数数据量大的情况下推荐使用对象传参
// 形式如下this.$store.commit("add", obj)
store 过滤器
这种叫法不准确,但是在形式上,store 提供的 getters 接口最后在结果上确实很像过滤器
var store = new Vuex.Store({ ?state: { ???count: 0 ?}, ?mutations: { ???add(state) { ?????state.count++ ???}, ???remove(state, num) { ?????state.count = state.count - (num.one + num.two) ???} ?}, ?getters: { ???show(state) { ?????return "加工一下 state 数据:" + state.count ???} ?}})
需要注意的是,getters 接口在也很类似于 computed,因为 state 的值只要发生变化,就会触发 getters 方法
JS——vuex 基本使用
原文地址:https://www.cnblogs.com/cnloop/p/9277809.html