【VUE3】setup语法糖(computed 使用+watch监听)

一、定义data

//定义data 
//vue2

<script>
	export default {
		data(){
			retrun{
			 aa:""
			}
		}
	}
</script>

//Vue3 通过 ref 和 rective 代替以前的 data 语法,在setup语法糖中直接使用,无需return 出去
<script setup>
	//首先需要引入
	import { ref , reactive } from "vue"
	//定义一个数据
	const aa = ref("") //ref(false) //ref([])//ref({})
	//查看或者修改的时候需要在数后面加一个value。
	console.log(aa.value)
	aa.value = 1
	
	//reactive 主要是用来处理复杂的数据类型,比如对象和数组。
	//所以当你传递的是非对象时,页面不会发生响应 
	//错误示范 
	// let error = reactive(err)
	//正确示范
	let right = reactive({
		name:"张三"
	})
	//修改值得时候
	right.name = "李四"
</script>

二、computed 使用

<template>
  <div class="box">
    <!-- 在上方调用即可,结果为169 -->
    {{add}}
  </div>
</template>
<script setup>
import { computed, ref } from "vue"; 
let num1 = ref(13);
let num2 = ref(13); // 设置个变量接收 
let add = computed(() => {  
	return num1.value * num2.value; 
});
</script>


三、watch监听

使用watch也需要引入,使用方式与vue2相差不大,不同的是,监听多个属性的时候,要写多个watch。

import { watch } from "vue"

watch(() => brand.brand, (newVal) => {
    console.log(newVal)
    })
}, { deep: true,immediate:true }
)

如果写到一起的话,就会出现其中一个值变化,下面的方法都会触发,不能独立监听。

watch(()=>[user.value, password.value],([newUser, newPassword],[oldUser, oldPassword])=>{
  console.log('我是新的user值'+newUser);
  console.log('我是旧的的user值'+oldUser);
  console.log('我是新的pass值'+newPassword);
  console.log('我是旧的的pass值'+oldPassword);
})



  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

都挺好,刚刚好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值