vuex 使用
一、什么是Vuex
Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化

二. 为什么要使用Vuex?
试想这样的场景, 比如一个Vue的根实例下面有一个根组件名为
App.vue, 它下面有两个子组件A.vue和B.vue, App.vue想要与A.vue或者B.vue通讯可以通过props传值的方式, 但是如果A.vue和B.vue之间的通讯就很麻烦了, 他们需要共有的父组件通过自定义事件进行实现, A组件想要和B组件通讯往往是这样的:
A组件说: "报告App老大, 能否帮我托个信给B组件" => dispatch一个事件给App
App组件说: "包在我身上, 它需要监听A组件的dispatch的时间, 同时需要broadcast一个事件给B组件"
B组件说: "信息已收到", 它需要on监听App组件分发的事件
三、实现
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vuex</title>
</head>
<script src="./vuex.js"></script>
<script src="./vue.js"></script>
<body>
<div id="app">
<say></say>
<counter></counter>
</div>
</body>
<script>
Vue.use(Vuex); //在创建Vue实例之前
// 注册一个全局组件
Vue.component('say', {
template: `<div>{{name}} {{age}} {{num}} <br/>
<p style='color:yellow' @click='changeNum'>点我</p>
<p style='color:pink' @click='changeNumAnsyc'>点我1</p>
</div>`,
data: function () {
return {
}
},
computed: {
name: function () {
return this.$store.state.name
},
age: function () {
return this.$store.getters.getAge
},
num: function () {
return this.$store.state.num;
}
},
mounted: function () {
console.log(this)
},
methods: {
changeNum: function () {
//在组件里提交
this.$store.commit('change', 10)
},
changeNumAnsyc: function () {
this.$store.dispatch('add', 5);
}
}
})
// 局部组件
const Counter = {
template: `<div style="color:red;">{{ count }}</div>`,
computed: {
count() {
return this.$store.state.num
}
}
}
var myStore = new Vuex.Store({
state: {
//存放组件之间共享的数据
name: "vuex",
age: 20,
num: 1
},
mutations: {
//显式的更改state里的数据 只能处理同步函数
change: function (state, a) {
// state.num++;
state.num += a;
console.log(state.num += a);
},
changeAsync: function (state, a) {
state.num += a;
console.log(state.num += a);
}
},
getters: {
//获取数据的方法
getAge: function (state) {
return state.age;
}
},
actions: {
// 可以处理异步函数
add: function (context, value) {
setTimeout(function () {
//提交事件
console.log("stop");
context.commit('changeAsync', value);
}, 1000)
}
}
});
new Vue({
el: "#app",
data: {
name: "小明"
},
components: {
Counter
},
store: myStore,
mounted: function () {
console.log(this) //
},
})
</script>
</html>
</html>

浙公网安备 33010602011771号