代码改变世界

vue 的 store 响应式原理

  muamaker  阅读(465)  评论(0编辑  收藏  举报

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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 中,很显然是会变化的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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>

  

 

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示