本文首发 https://shudong.wang/10382.html打算实现一个vuex先从第一步开始,实现一个相似$store 的惟一全局变量,父组件和子组件均可以随时调用。
下面咱们来实现html
$options.parent
当咱们在子组件调用的时候,能够把咱们设置的变量,挂在到this上面
下面实现一个 $stark 挂在到全局变量
if (this.$options.stark) { this.$stark = this.$options.stark } else if (this.$options.parent && this.$options.parent.$stark) { this.$stark = this.$options.parent.$stark }
mixin.js
Vue.mixin({ beforeCreate: starkInit }) // shudong.wang function starkInit() { const options = this.$options if (options.stark) { this.$stark = typeof options.stark === 'function' ? options.stark() : options.stark } else if (options.parent && options.parent.$stark) { this.$stark = options.parent.$stark } }
stark.js
import applyMixin from './mixin' export class Stark { constructor(options = {}) { this.options = options } get state() { return this.options.state } } export function install(_Vue) { applyMixin(Vue) }
index.js
import { Stark, install } from './stark' export default { Stark, install, }
state.js
export const state = { count: 10 }
import Vue from 'vue' import App from './App.vue' import stark from './stark' Vue.config.productionTip = false new Vue({ render: h => h(App), stark, }).$mount('#app')
created() { console.log('App',this.$stark); },