热门搜索 :
考研考公
您的当前位置:首页正文

如何实现vuex(一期)

来源:东饰资讯网

随着前端业务日益复杂,组件数量不断增加,组件之间的通信变得越来复杂,兄弟组件之间跨级传参,状态修改得追踪,都是一个难题 VUEX解决了这个问题,然后如何实现一个简单得vuex呢,state是如何在不同组件之间被watch得,值得去研究。

vue mixin 了解一下

混入 (mixins) 是一种分发 Vue 组件中可复用功能的非常灵活的方式。


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

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

输出:// => "hello!"
全局混入: 在new vue对象时,会自动执行created这个方法,如果new vue里面还有create 就会先执行mixin,再执行实例里面的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的时候执行created的方法,Vue.prototype.$store = bus,相当于在原型链上添加一个共享对象。
  2. Vue 和 VueComponent 的原型链上指向同一个store,这样不同组件之间就能共享一个state。
  3. $strore 指向的还是一个vue对象,保证修改可以被监听到。

著作权声明

Top