<script setup>
//原始响应式数组
impot { ref } from 'vue'
//导入computed
imput { computed } from 'vue'
const list = ref([1,2,3,4,5,6,7,8,])
//执行函数return计算之后的值 变量接收
const computedList = computed(()=>{
//根据一个数据计算得到一个新的数据
return list.value.filter(item => item > 2)
})
setTimeout(() =>{
list.value.push(9,10)
},5000)
</script>
<template>
<div>
原始响应数组- {{ list }}
</div>
<div>
计算属性数组 - {{ computedList }}
</div>
</template>
计算属性不应该有‘副作用’,例如异步请求,修改dom。计算属性应该是只读的
watch函数:作用:监听一个或者多个数据的变化,数据变化时执行回调函数。俩个额外参数:1.immediate(立即执行)2.deep(深度监听)
<script setup>
import { ref, watch } from 'vue';
const count = ref(0)
const setCount = () =>{
count.value++
}
//TODO:watch侦听单个数据源
//ref对象不需要加.value
watch(count,(newVal,oldVal) =>{
console.log('count变化了',newVal,oldVal)
})
</script>
<template>
<div>
<button @click="setCount">+{{ count }}</button>
</div>
</template>
侦听多个响应式数据的变化,不管那个数据变化都需要执行回调
<script setup>
//侦听多个数据变化
import { ref,watch } from 'vue';
const count = ref(0)
const changeCount = () => {
count.value++
}
const name = ref('cp')
const changeName = () => {
name.value = 'pc'
}
//TODO:watch侦听多个数据源
watch(
[count,name],
(
[newCount,newName],
[oldCount,oldName]
) => {
console.log('count或者name变化了',[newCount,newName],
[oldCount,oldName])
})
</script>
<template>
<div>
<button @click="changeCount">修改count--{{ count }} </button>
</div>
<div>
<button @click="changeName">修改name--{{ name }}</button>
</div>
</template>