如何實現(xiàn)vuex(一期)

隨著前端業(yè)務日益復雜,組件數(shù)量不斷增加,組件之間的通信變得越來復雜,兄弟組件之間跨級傳參,狀態(tài)修改得追蹤,都是一個難題 VUEX解決了這個問題,然后如何實現(xiàn)一個簡單得vuex呢,state是如何在不同組件之間被watch得,值得去研究。

vue mixin 了解一下

混入 (mixins) 是一種分發(fā) Vue 組件中可復用功能的非常靈活的方式。


Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})

輸出:// => "hello!"
全局混入: 在new vue對象時,會自動執(zhí)行created這個方法,如果new vue里面還有create 就會先執(zhí)行mixin,再執(zhí)行實例里面的create.


        // 子組件 a
        const childA = {
          data: function(){
            return {a:1}
          },
          created: function(){
            console.log('childA',this);
          },
          template: '<button @click="handleClick">click me</button>',
          methods: {
            handleClick () {
                console.log(this)
              this.$store.state.count += 1
            }
          }
        };

        // 子組件 b
        const childB = {
          data: function(){
            return {b:2}
          },
          created: function(){
            console.log('childB',this);
          },
          template: '<div>count: {{ count }}</div>',
          computed: {
            count () {
              return this.$store.state.count
            }
          }
        };

        class Store {
            constructor (Vue, options) {
            console.log('new Vue');
            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
                }
              }
            })
          }
        };

        const store = new Store(Vue, {
          state: {
            count: 0
          }
        })

        new Vue({
          el: '#app',
          data: function(){
            return {c:1}
          },
          created: function(){
            console.log('vue',this);
          },
          components: {
            'child-a': childA,
            'child-b': childB
          },
          store: store
        });

代碼解析:

  1. 初始化VUE的時候執(zhí)行created的方法,Vue.prototype.$store = bus,相當于在原型鏈上添加一個共享對象。
  2. Vue 和 VueComponent 的原型鏈上指向同一個store,這樣不同組件之間就能共享一個state。
  3. $strore 指向的還是一個vue對象,保證修改可以被監(jiān)聽到。

著作權聲明

原文地址: 覃國雷的博客

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容