1、mixin.js
const applyMixin=(Vue)=>{
Vue.mixin({
beforeCreate:vuexInit
})
}
// 组件的创建过程 是先父后子
function vuexInit(){
const options=this.$options;
if(options.store){
// 根实例
this.$store=options.store;
}else if(options.parent && options.parent.$store){
// 子组件
this.$store=options.parent.$store;
}
}
export default applyMixin;
// vue-router 是把所有属性定义到了根实例 所有组件都能拿到这个根,通过根实例获取这个属性
// vuex 给每个组件都定义一个$store 属性 指向的是同一个人。
2、index.js
// 主文件的作用一般就是整合操作
// 两种方式都可以 可以采用默认导入,也可以采用解构导入
import {Store,install} from './store';
export default {
Store,
install
}
export {
Store,
install
}
3、store.js
import applyMixin from './mixin';
let Vue;
class Store{
constructor(options){
console.log(options);
}
}
const install=(_Vue)=>{
Vue=_Vue;
console.log('install'); // vue-router 调用instal目的 注册了全局组件 注册了原型方法 mixin=>
// router 实例绑定给了所有组件
applyMixin(Vue);
}
export {
Store,
install
}
4、目录结构
![](https://img-blog.csdnimg.cn/20200925025254638.png)