• 【vue3】监控响应: reactive/watch/watchEffect/provide.inject/computed


    Vue3 监控响应变化

    通过reactive

    reactive定义文档

    • reactive定义: 接收一个普通对象然后返回该普通对象的响应式代理。等同于 2.x 的 Vue.observable()
    • reactive实现: proxy + effect
    /*
      App.vue
      同一个组件中, 定义一个reactive对象并直接返回, 在templete绑定会直接响应对应的数据变化
    */
    
    <templete>
      <div> {{ x.a }} </div>
    </templete>
    
    <script lang="ts">
    import {
      defineComponent,
      onMounted,
      reactive
    } from "vue";
    
    interface testStruct {
      a: number;
      b: number;
    }
    
    export default defineComponent({
      name: "App",
      components:{},
      setup(){
        const x = reactive<testStruct>({
          a: 0;
          b: 0;
        })
      };
    
      onMounted(() => {
        console.log("app onMounted");
        setInterval(countAdd, 1000);
      );
    
      function countAdd() {
        x.a += 1;
        x.b -= 1;
      }
    
      return { a };
    })
    </script>
    
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>
    
    

    通过ref

    ref定义文档

    • ref定义: 接受一个参数值并返回一个响应式且可改变的ref对象。ref 对象拥有一个指向内部值的单一属性 .value
    • ref实现:
      传入参数是否为对象? (y/n) :
      • y : 内部通过reactive转换,将其作为ref对象返回
      • n : 直接构造一个ref对象返回

    通过computed

    computed定义文档

    • computed定义: 定义计算属性

    • 参数

      • 传入一个 getter 函数,返回一个默认不可手动修改的 ref 对象。
      • 传入一个拥有 get 和 set 函数的对象,创建一个可手动修改的计算状态。
    • computed实现: 内部也是通过effect响应

    • 使用场景: 当需要一个值x, 且x随其他值的变化而变化, 则可将x放入computed

    通过effect

    effect定义文档

    • effect定义: 主要负责收集依赖, 更新依赖(也是reactive核心)

    父子组件的通信

  • 相关阅读:
    全能VIP音乐在线解析
    wordpress插件推荐
    day 34 IO模型
    day 33 协程、 socketserver模块
    day 32-2 练习
    day 32-2 并发编程——认识线程(下)
    day 32 练习
    day 32 并发编程——认识线程(上)
    day 31-1 练习
    day 31-1 守护进程、互斥锁、队列、生产消费模型
  • 原文地址:https://www.cnblogs.com/sakanastar/p/15899696.html
Copyright © 2020-2023  润新知