计算属性
方式一
<script setup lang="ts">
import {computed ,ref} from "vue"
const name = ref("你好")
const helloName = computed(()=>name.value+"vue3"); // 你好 vue3
</script>
方式二
<template>
<h1>this is hello world</h1>
<h2>{{ newName}}</h2>
<button @click="newName='vue3'">click</button>
</template>
<script setup lang="ts">
import {computed ,ref} from "vue"
const name = ref("你好");
const newName = computed({
get(){
return name.value
},
set(value:string){
name.value = "hello"+value // 你好 vue3
}
})
</script>
watch 监听
监听基本类型
<script setup lang="ts">
import {watch,ref} from "vue"
const name = ref("zhangsan")
const age = ref(18)
watch(name,(newValue,oldvalue)=>{})
//同时监听多个变量
watch([name,age],(newVal,oldVal)=>{})
</script>
监听对象
<template>
<h1>this is hello world</h1>
<h2>{{ data.name }}</h2>
<button @click="handleClick">click</button>
</template>
<script setup lang="ts">
import {reactive ,watch} from "vue"
const data = reactive({
name:"zhangsan"
})
const handleClick = ()=>{
data.name = "lisi"
}
watch(data,(newValue,oldValue)=>{
console.log(newValue);
console.log(oldValue);
})
</script>
- 如果使用 reactive 监听对象无需使用 deep 模式
- watch 监听对象 newValue 和 oldValue 的值都是最新的
如果监听一个对象的具体属性,需要使用回调函数
<script setup lang="ts">
import {reactive ,watch} from "vue"
const data = reactive({
name:"zhangsan"
})
const handleClick = ()=>{
data.name = "lisi"
}
watch(()=>data.name,(newValue,oldValue)=>{})
</script>
深度配置
- deep:true 深度监听
- flush:’pre’ // pre更新前调用 sync 同步调用 post 更新后调用
- immediate:true // 立即执行
watch高级侦听器
示例
<template>
<h1>this is hello world</h1>
<h2>{{ name }}</h2>
<button @click="handleClick">click</button>
<button @click="handleStop">停止监听</button>
</template>
<script setup lang="ts">
import {watchEffect,ref} from "vue"
const name = ref("zhangsan")
const handleClick = ()=>{
name.value = "lisi"
}
const handleStop = ()=>{
stopWatch()
}
const stopWatch = watchEffect((oninvalidate)=>{
oninvalidate(()=>console.log("更新前调用"))
console.log(name.value);
})
</script>
深度配置 [ 第二个参数 ]
<script setup lang="ts">
import {watchEffect,ref} from "vue"
watchEffect((oninvalidate)=>{
oninvalidate(()=>console.log("更新前调用"))
console.log(name.value);
},{
flush:'pre' , // pre更新前调用 sync 同步调用 post 更新后调用
onTrigger(e){debugger;} // 用于调试的 debugger 控制台
})
</script>