Computed properties
The most basic grammar
Computed properties are static, and the basic syntax is as follows
import {computed,toRef} from 'vue'
let val = ref('原始值')
let computedVal = computed(()=>{
return toRef(val.value+'aaa')
})
demo
<template>
<h3>计算属性</h3>
<el-input v-model="value1"></el-input>
<p>新的数据1{
{ value1Computed }}</p>
<p>新的数据2{
{ value2Computed }}</p>
<p>set触发的{
{ value2 }}</p>
</template>
<script setup lang="ts">
let value1:any = ref('数据1')
let value2:any = ref('数据2')
//函数形式
let value1Computed = <ComputedRef>computed(()=>{
return toRef(value1.value+'哈哈哈')
})
//get&set方法
let value2Computed = <ComputedRef>computed({
get(){
return value1Computed.value.value+'呵呵呵'
},
set(value){
value2.value = value+'呵呵呵'
}
})
</script>
Data monitoring
Data monitoring is dynamic
The most basic grammar
let value1= ref('数据1')
watch(value1,(newVal,oldVal)=>{
console.log(newVal,oldVal,'截取到单一值的变化')
})
demo
In addition to monitoring a single value, data monitoring can also monitor a specific attribute of the data, or deeper reference type data, or multiple data. The code is as follows
<template>
<el-input v-model="value1"></el-input>
<el-input v-model="value2"></el-input>
<el-input v-model="obj.obj.name"></el-input>
<el-input v-model="obj.obj.obj.name"></el-input>
<el-input v-model="reactiveObj.value"></el-input>
</template>
<script setup lang="ts">
let value1= ref('数据1')
watch(value1,(newVal,oldVal)=>{
console.log(newVal,oldVal,'截取到单一值的变化')
})
let value2 = ref('数据2')
watch([value1,value2],(newVal,oldVal)=>{
console.log(newVal,oldVal,'截取多个值的变化')
})
let obj = ref({obj:{
name:'深度1',
obj:{
name:'深度2'
}
}})
watch(obj,(newVal,oldVal)=>{
console.log(newVal,oldVal,'截取值深度的变化')
},{
immediate:true,
deep:true
})
let reactiveObj = reactive({
value:'reactive定义的响应值'
})
watch(reactiveObj,(newVal,oldVal)=>{
console.log(newVal,oldVal,'reactive的值变化')
})
watch(()=>reactiveObj.value,(newVal,oldVal)=>{
console.log(newVal,oldVal,'对象内的某个值')
})
</script>