学习笔记-reactive, ref, toRef, toRefs

914 阅读2分钟

reactive

用来创建简单的响应式数据对象

不需要 .value获取属性值

数据更新 -> 视图更新

import { reactive } from 'vue'
export default {
  setup() {
    // 创建响应式对象
    let numObj = reactive({num: 0})
    function addCount(){
      numObj.num++
    }
    function cutDown(){
      numObj.num--
    }
    // 将响应式对象numObj return出去, 供组件使用
    return {
      numObj, addCount, cutDown
    }
  },
}

 

ref

ref就是通过reactive包装了一个对象, 然后将值传到该对象的value属性,

在setup中使用时, 需要 .value

数据更新 -> 视图更新

<template>
  <div class="about">
    <h1>计数器:</h1>
    <h1>{{num}}</h1>


    <button @click="addCount">加一</button>
    <button @click="cutDown">减一</button>
  </div>
</template>

 

import { ref  } from 'vue'
export default {
  setup() {
    let num = ref(0)
    function addCount(){
      num.value++
      console.log(num);
    } 
    
    function cutDown(){
      num.value--
      console.log(num);
    }
    return {
      num, addCount, cutDown
    }
  },
}

注意: 这里使用 .value是在setup函数中访问 ref 包装后的对象时才需要加的,在 template 模板中访问时是不需要的

 

什么时候用ref和reactive呢?

  1. 基本数据类型, 或者单值对象( {num: 0} ) 使用ref
  2. 引用数据类型, 使用reactive

 

toRef

toRef是将对象中的某个值转化为响应式数据,

接收两个参数, 一个是obj对象, 另一个是对象中要转换的属性名( 字符串类型 )

<template>
  <div class="about">
    <h1>计数器:</h1>
    <h1>{{numObj.num}}</h1>


    <button @click="addCount">加一</button>
    <button @click="cutDown">减一</button>
  </div>
</template

 

<script>
import { toRef  } from 'vue'
export default {
  setup() {
    let obj = { num: 0 }
    let numObj = toRef(obj, 'num')
    console.log(numObj.value);
    function addCount(){
      numObj.value++
      console.log(numObj.value);
      console.log(obj);
    } 
    
    function cutDown(){
      numObj.value--
      console.log(numObj.value);
      console.log(obj);
    }
    return {
      numObj, addCount, cutDown
    }
  },
}

toRefs

将传入的对象的所有属性值都转化成响应式对象, 传入一个参数, 即obj对象

不会更新视图

<template>
  <div class="about">
    <h1>计数器:</h1>
    <h1>{{numObj.num}}</h1>


    <button @click="addCount">加一</button>
    <button @click="cutDown">减一</button>
  </div>
</template>

 

import { toRefs  } from 'vue'
export default {
  setup() {
    let obj = { num: 0 }
    let numObj = toRefs(obj)
    console.log(numObj.num.value);
    function addCount(){
      numObj.num.value++
      console.log(numObj.num.value);
      console.log(obj);
    } 
    
    function cutDown(){
      numObj.num.value--
      console.log(numObj.num.value);
      console.log(obj);
    }
    return {
      numObj, addCount, cutDown
    }
  },
}

 

 

总结

方法名参数是否需要.value原始值是否改变视图是否更新
reactive引用类型
ref基本类型
toRef(obj, 'keyStr')
toRefs引用数据类型

Exp:

  1. 这里指的 .value 是在 setup 函数中访问 ref 包装后的对象时才需要加的,在 template 模板中访问时是不需要的,因为在编译时,会自动识别其是否为 ref 包装过的
  2. 视图改变了, 原始值没有改变, 说明是对原数据的一个拷贝, 不会影响原始值。原始值改变了, 说明是对原数据的一个引用, 会影响原始值