vuex实现原理实际上是通过Vue的实例化来实现
这里通过计数器来说明
首先实例化两个Vue对象,通过他测试是否能统一管理状态#root和 #root2
new Vue({
el:'#root',
computed:{
data(){
return this.$store.state.count
}
},
});
new Vue({
el:'#root2',
computed:{
data2(){
return this.$store.state.count
}
}
});
接下就是实例化一个Vue对象来统一管理状态
function registerPlugin(Vue){
const myVuex = {};
myVuex._vm = new Vue({ // 实例化一个vue对象
data(){
return {
count : 0
}
}
});
myVuex.state = myVuex._vm;
myVuex.dispatch = (name)=>{
console.log(myVuex);
myVuex.actions[name]()
};
myVuex.actions = {
//调用mutation
addPoint:()=>{
myVuex.mutations.ADDCOUNT()
},
reducePoint:()=>{
myVuex.mutations.REDUCECOUNT()
}
};
myVuex.mutations = {
//改变state状态
ADDCOUNT(){
myVuex.state.count += 1
},
REDUCECOUNT(){
myVuex.state.count-=1
}
};
function init(){
this.$store = myVuex; //this指向Vue对象
}
Vue.mixin({ //每当实例化Vue对象时都会调用
beforeCreate:init // 注意这里init不能加括号,加上()后赋值给beforeCrete是函数的返回值,返回值为空则赋值的是undefined,,
//另外在加上括号赋值后,init函数将回在赋值的同时被调用,其this指向也将指向window !!!!!
});
}
Vue.use(registerPlugin)
接下来通过调用this.$store.dispatch('addPoint');
就可以改变统一管理的状态值
全部代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<p id="root">{{data}}</p>
<p id="root2">{{data2}}</p>
<div id="root3">
<button @click="addPoint()">+</button>
<button @click="reducePoint()">-</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
function registerPlugin(Vue){
const myVuex = {};
myVuex._vm = new Vue({ // 实例化一个vue对象
data(){
return {
count : 0
}
}
});
myVuex.state = myVuex._vm;
myVuex.dispatch = (name)=>{
console.log(myVuex);
myVuex.actions[name]()
};
myVuex.actions = {
//调用mutation
addPoint:()=>{
myVuex.mutations.ADDCOUNT()
},
reducePoint:()=>{
myVuex.mutations.REDUCECOUNT()
}
};
myVuex.mutations = {
//改变state状态
ADDCOUNT(){
myVuex.state.count += 1
},
REDUCECOUNT(){
myVuex.state.count-=1
}
};
function init(){
this.$store = myVuex; //this指向Vue对象
}
Vue.mixin({ //每当实例化Vue对象时都会调用
beforeCreate:init // 注意这里init不能加括号,加上()后赋值给beforeCrete是函数的返回值,返回值为空则赋值的是undefined,,
//另外在加上括号赋值后,init函数将回在赋值的同时被调用,其this指向也将指向window !!!!!
});
}
Vue.use(registerPlugin)
new Vue({
el:'#root',
computed:{
data(){
return this.$store.state.count
}
},
});
new Vue({
el:'#root2',
computed:{
data2(){
return this.$store.state.count
}
}
});
new Vue({
el:'#root3',
methods:{
addPoint(){
this.$store.dispatch('addPoint');
},
reducePoint(){
this.$store.dispatch('reducePoint');
}
}
})
</script>
</body>
</html>