vue3 数据响应更复杂了吗?

vue数据响应( ref 和 reactive )

Ⅰ. ref 和 reactive 的用法

ref常用于简单数据类型,(不建议 引用数据类型)。
reactive常用于引用类型 。

<template>
   <p> {
    
    {
    
     name }} </p>
   <p> {
    
    {
    
     state.age }} </p>
</template>
import {
    
     ref , reactive }  from 'vue';
setup(){
    
    
	const name =  ref( '张三' );
	const state =  reactive({
    
     age:17 });
	
    name.value = '李四'; // 修改
    state.age++;   // 修改
                
	return {
    
     name , state }			
  }

我们可以看出:
① ref 在 js 中需要加 value 属性, 相当于 => const name = reactive({ value : 5 })
② ref 在 html 却可以省略 value 属性 ,是因为根据 _v_isRef 判断省去了 => 如图:

在这里插入图片描述

Ⅱ. 通过ref 和 reactive 模拟vue2的写法
直接创建一个对象,return 这个对象就有了vue2的味道了

<template>
   <p> {
    
    {
    
     name }} </p>
   <p> {
    
    {
    
     age }}  </p>
   <button @click='add' > 增加 </button>
</template>
import {
    
     reactive }  from 'vue';
setup(){
    
    
	const data = reactive({
    
    
		name:'张三',
		age:'18',
		add:function(){
    
    	 this.age++;  }  //或data.age++;
	});
	
	return data;		
  }

注意:

① 在返回时如果通过 解构return 就会 失去响应 =>如:

......
setup(){
    
    
	const data = reactive({
    
    
		name:'张三',
		age:'18',
	});
	return {
    
     ...data };	
  }
......

Ⅱ. toRefs的应用
②正确写法,我们可以通过toRefs ,让解构出来的对象,再次成为proxy对象进行响应 =>如:

......
import {
    
     reactive , toRefs }  from 'vue';
setup(){
    
    
	const data1 = reactive({
    
    
		name:'张三',
		age:'18',
	});
	const data2 = reactive({
    
     
		height:180,
		weight:'60kg',
	})
	return {
    
     ...toRefs(data1), ...toRefs(data2)};	
  }
......

学费了,记得点赞!!

猜你喜欢

转载自blog.csdn.net/weixin_42232622/article/details/125642401