詳解如何實現(xiàn)一個簡單的 vuex
首先我們需要知道為何要使用 vuex。父子組件通信用 prop 和自定義事件可以搞定,簡單的非父子組件通信用 bus(一個空的 Vue 實例)。那么使用 vuex 就是為了解決復雜的非父子組件通信。
僅僅會使用 vuex 沒什么,看過文檔敲敲代碼大家都會。難道你就不想知道 vuex 是如何實現(xiàn)的?!
拋開 vuex 的源碼,我們先來想想如何實現(xiàn)一個簡單的 "vuex"。有多簡單呢,我不要 getter、mutation、action 等,我只要 state 就行了。
非父子組件通信
在實現(xiàn)之前,我們得來溫故一下 bus 的實現(xiàn),借用官網(wǎng)的例子:
var bus = new Vue()
// 觸發(fā)組件 A 中的事件
bus.$emit('id-selected', 1)
// 在組件 B 創(chuàng)建的鉤子中監(jiān)聽事件
bus.$on('id-selected', function (id) {
// ...
})
遙想當年,實例化后的 bus 不知放哪好,最后無奈將其放到了 window 下,一直 window.bus 的使用。雖然這樣也沒問題,但還是影響到了全局作用域。
突然的某一天,我發(fā)現(xiàn)可以掛載在 vue 的根實例下(從此告別 window.bus),于是便有了:
var app = new Vue({
el: '#app',
bus: bus
})
// 使用 bus
app.$options.bus
// or
this.$root.$options.bus
然后又發(fā)現(xiàn)了,bus 其實不只是 on 事件才可以通信。其實 bus 是一個 Vue 實例,其中 data 是響應的。比如在 app 這個根實例下有兩個非父子組件,都使用到了 bus 的 data,那么它們是響應同步的。
var bus = new Vue({
data: {
count: 0
}
})
以上,子組件 a 修改了 count,如果子組件 b 有用到 count,那么它就能響應到最新 count 的值。
說了這么多,你還沒發(fā)現(xiàn)嗎?這個不就是實現(xiàn)了非組件之間通信,vuex 的 state 嗎?!
封裝 bus
是的,把剛剛的 bus 封裝一下,這個就是一個最簡單的 "vuex" (僅僅只有 state 的功能)。首先,我們將有一個根實例 app ,實例下有兩個非父子組件 childA 和 childB 。
html 代碼的實現(xiàn)如下:
<div id="app"> <child-a></child-a> <child-b></child-b> </div>
非父子組件的實現(xiàn)
然后是兩個非父子組件和 app 的實現(xiàn),子組件都使用到了 bus 的 count,這里用 store.state 表示,跟 vuex 一致:
// 待實現(xiàn)
const store = new Store(Vue, {
state: {
count: 0
}
})
// 子組件 a
const childA = {
template: '<button @click="handleClick">click me</button>',
methods: {
handleClick () {
this.$store.state.count += 1
}
}
}
// 子組件 b
const childB = {
template: '<div>count: {{ count }}</div>',
computed: {
count () {
return this.$store.state.count
}
}
}
new Vue({
el: '#app',
components: {
'child-a': childA,
'child-b': childB
},
store: store
})
看到代碼里還有一個 Store 待實現(xiàn)。所需要的參數(shù),因為這里懶得用 Vue.use() ,所以直接將 Vue 作為參數(shù)傳入以供使用,然后第二個參數(shù)跟我們使用 vuex 傳入的參數(shù)一致。
Store 的實現(xiàn)
接下來就是 Store 的實現(xiàn),兩步實現(xiàn):
- 創(chuàng)建一個 bus 實例;
- 讓子組件都能訪問到 this.$store。
第 1 步驟上面已經(jīng)有了,第 2 步驟主要用到了 Vue.mixin 來全局混入,但僅僅只是找到有 store 的根實例并賦值 Vue 原型上的 store,也能夠讓根實例 app 不用專門寫 mixins 混入。
class Store {
constructor (Vue, options) {
var bus = new Vue({
data: {
state: options.state
}
})
this.install(Vue, bus)
}
install (Vue, bus) {
Vue.mixin({
beforeCreate () {
if (this.$options.store) {
Vue.prototype.$store = bus
}
}
})
}
}
實現(xiàn)的 Store 就是一個簡單的 "vuex",它擁有了 vuex 的 state,足夠讓非父子組件之間進行簡單通信。
在 Store 的構(gòu)造函數(shù)里創(chuàng)建一個 bus 實例,并將其注入 Vue 的原型,實現(xiàn)了組件都能訪問到 this.$store 即 bus 實例。 this.$store 就是一個 Vue 實例,所以訪問了 this.$store.state.count 實際上就是訪問到了 data,從而實現(xiàn)了非父子組件之間的響應同步。全部源碼參考這里 。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue2 mint-ui loadmore實現(xiàn)下拉刷新,上拉更多功能
這篇文章主要介紹了vue2 mint-ui loadmore實現(xiàn)下拉刷新,上拉更多功能,需要的朋友可以參考下2018-03-03
vue-router next(false) 禁止訪問某個頁面時,不保留歷史訪問記錄問題
這篇文章主要介紹了vue-router next(false) 禁止訪問某個頁面時,不保留歷史訪問記錄問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

