本文首發 shudong.wang/10382.htmlhtml
打算實現一個vuex先從第一步開始,實現一個相似$store 的惟一全局變量,父組件和子組件均可以隨時調用。 下面咱們來實現vue
$options.parent
複製代碼
當咱們在子組件調用的時候,能夠把咱們設置的變量,掛在到this上面 下面實現一個 $stark 掛在到全局變量vuex
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.jsapi
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.jsbash
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.jsapp
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);
},
複製代碼