Vue3总结

作者: 进击韭菜 | 来源:发表于2021-09-08 16:19 被阅读0次

ref、reactive、toRef、toRefs的区别

API 是否更新视图 是否改变原始数据 是否可以解构使用
ref (引用类型等同于reactive:是,基本类型:否)
reactive 否(失去响应性)
toRef
toRefs
<template>
    <p>
      ref:
      <button @click="increaseAgeByRef">{{ refTemp }}</button>
    </p>
    <p>
      toRef:
      <button @click="increaseAgeByToRef">{{ toRefTemp }}</button>
    </p>
    <p>
      toRefs:
      <button @click="increaseAgeByToRefs">{{ toRefsTemp.age }}</button>
    </p>
    <p>
      reactive:
      <button @click="increaseAgeByReactive">{{ reactiveTemp.age }}</button>
    </p>
    <div>
      <p>name: {{ name }}</p>
      <p>age: {{ age }}</p>
      state-age:<input type="text" v-model="age" @input="inputChange">
    </div>
</template>
import {ref, toRef, reactive, toRefs,} from 'vue'

export default {
  name: 'demo',
  setup() {
    const user = { name: 'test', age: 18 }
    const refTemp = ref(user.age);
    const toRefTemp = toRef(user, 'age');
    const reactiveTemp = reactive(user)
    const toRefsTemp = toRefs(user);

    // 依次点击
    const increaseAgeByRef = () => {
      refTemp.value++    // 视图更新 19
      console.log("user:")
      console.log(user)  // 不改变原始数据{ name: 'test', age: 18 }
    }
    const increaseAgeByToRef = () => {
      toRefTemp.value++ // 视图不更新 18
      console.log("user:")
      console.log(user) // 改变原始数据{ name: 'test', age: 19 }
    }
    const increaseAgeByToRefs = () => {
      toRefsTemp.age.value++ // 视图不更新 18
      console.log("user:")
      console.log(user) // 改变原始数据{ name: 'test', age: 20 }
    }
    const increaseAgeByReactive = () => {
      reactiveTemp.age++ // 视图更新 21,toRef、toRefs和input视图更新 21
      console.log("user:")
      console.log(user) // 改变原始数据{ name: 'test', age: 21 }
    }
    // input输入211, 视图不更新
    const inputChange = () => {
      console.log("user:")
      console.log(user) // 改变原始数据{ name: 'test', age: 211 }
    }
   
    return {
      refTemp,
      reactiveTemp,
      toRefTemp,
      toRefsTemp,
      increaseAgeByRef,
      increaseAgeByReactive,
      increaseAgeByToRef,
      increaseAgeByToRefs,
      ...toRefsTemp,
      inputChange
    }
  }
}

既要改变数据后更新视图,又想解构使用。比如表格需要创建的响应式数据,可以这样写:

export default {
  setup() {
    const data= { list: [], page: 1, size: 10, isLoading: false }
    const state= reactive(data)
    return {
      ...toRefs(state)
    }
  }
}

相关文章

网友评论

    本文标题:Vue3总结

    本文链接:https://www.haomeiwen.com/subject/ugvvwltx.html