• vue 的 store 响应式原理


    一、先看如下代码, 无论你点击多少次按钮,结果始终是 10 。

    <template>
      <div class="about">
        <button  @click="onAdd">点击</button>
        <p>结果 {{count}}</p>
      </div>
    </template>
    <script>
    
    const Store = {
      count:1
    }
    export default {
      computed:{
        count(){
          return Store.count * 10
        }
      },
      methods:{
        onAdd(){
          Store.count = Store.count+1;
        }
      }
    }
    </script>
    

     

    二、在 vue store 中,很显然是会变化的

    <template>
      <div class="about">
        <button  @click="onAdd">点击</button>
        <p>结果 {{count}}</p>
      </div>
    </template>
    <script>
    
    import Vue from "vue";
    class Store{
      constructor(opt={}){
        let state = opt.state;
        this.mutations = state.mutations || {};
        
        this.vmKey = Symbol('this._vm');
        // 响应式 核心 
        this[this.vmKey] = new Vue({
          data(){
            return {
              state:state
            }
          }
        });
      }
      get state (){
         return  this[this.vmKey].state;
      }
      commit(key,params){
         this.mutations[key] && this.mutations[key].call(this, {state:this[this.vmKey].$state} ,params);
      }
    }
    
    let store = new Store({
      state:{
        count:1
      }
    });
    
    export default {
      computed:{
        count(){
          return store.state.count * 10
        }
      },
      methods:{
        onAdd(){
         store.state.count = store.state.count+1;
        }
      }
    }
    </script>
    

      

    store 的核心就是,构造了一个 new Vue , 利用 Vue 的数据劫持。构造一个响应式的数据。

    三、其实还可以用 Vue 提供的 API 构建一个响应式数据 Vue.observable

    <template>
      <div class="about">
        <button  @click="onAdd">点击</button>
        <p>结果 {{count}}</p>
      </div>
    </template>
    <script>
    
    import Vue from "vue";
    const store = Vue.observable({ count: 0 })
    
    export default {
      computed:{
        count(){
          return store.count * 10
        }
      },
      methods:{
        onAdd(){
         store.count = store.count+1;
        }
      }
    }
    </script>
    

      

     

  • 相关阅读:
    ASP.NET(C#) DataSet数据导出到Excel
    GridView生成导出EXECL
    Gridview 手动排序实现
    用DirectoryInfo搜索文件夹时过滤隐藏文件夹
    为 DropDownList 选项添加背景或样式 收
    IIS中 CS0016: 未能写入输出文件 …….*.dll拒绝访问
    singletontheorylazy.cs
    adaptertwowayseabird.cs
    StatefulLabel.cs
    LifecycleControl.cs
  • 原文地址:https://www.cnblogs.com/muamaker/p/16203375.html
Copyright © 2020-2023  润新知