vue3笔记----响应式函数(ref,reactive)

一vue3.x定义响应式数据需要使用ref函数或reactive函数

1.ref

ref 实现响应式还是通过Object.defineProperty添加getter和setter,所以使用ref实现响应式的数据最好是基本类型的

<template>
  <div>num的数字是{
   
   {num}}</div> 
  <!-- 页面中使用num值得时候不用.value -->
  <button @click="changeNum">改变数字</button>
</template>

<script>
// vue3.x定义响应式数据需要使用ref函数或reactive函数
import { ref } from "vue"; //可以通过ref响应
// 格式: const 数据名 = ref(初始值)
export default {
  setup() {
    // let num = 10; //num是不能做到响应
    const num = ref(10); //返回的是一个对象,读取值要使用.value
    const changeNum = () => {
      console.log("改变数字");
      //   num++;
      num.value++;
    //   console.log(num); //值变了,但不能响应
    };
    return {
      num,
      changeNum,
    };
  },
};
</script>

<style>
</style>

2.reactive

reactive 实现响应式,通过Proxy

<template>
  <div>完整的对象{
   
   {preson}}</div>
  <div>姓名:{
   
   {preson.name}}</div>
  <div>年龄:{
   
   {preson.age}}</div>
  <div>性别:{
   
   {preson.sex}}</div>
  <hr />
  <button @click="preson.age++">增加年龄</button>
  <button @click="preson.sex = '男'">添加性别</button>
</template>

<script>
import { reactive } from "vue";
//ref 实现响应式还是通过Object.defineProperty添加getter和setter
// reactive 实现响应式,通过Proxy
export default {
  setup() {
    const preson = reactive({
      name: "zs",
      age: 20,
    });
    return {
      preson,
    };
  },
};
</script>

<style>
</style>

猜你喜欢

转载自blog.csdn.net/m0_63237100/article/details/131397339