1. computed 计算属性
<template>
<div>
{{ name.value }}{{ helloName.value }}
</div>
</template>
<script>
import { defineComponent, ref, computed } from '@vue/composition-api'
export default defineComponent({
setup () {
let name = ref('')
// computed 接受一个箭头函数
let helloName = computed(() => {
return name.value ? `${name.value}!hello` : ''
})
setTimeout(() => {
name.value = 'zfb'
}, 2000)
return {
helloName,
name
}
},
})
</script>
<style scoped>
</style>
computed 之 set/get
<template>
<div>
{{ name.value }}{{ helloName.value }}
</div>
</template>
<script>
import { defineComponent, ref, computed } from '@vue/composition-api'
export default defineComponent({
setup () {
let name = ref('')
// computed 接受一个对象
let helloName = computed({
get: () => {
return name.value ? `${name.value}!hello` : ''
},
// helloName 重新设置值时候触发
set: (value) => {
console.log(`helloName new value: ${value}`)
}
})
setTimeout(() => {
name.value = 'zfb'
// 触发 computed set
helloName.value = 'hhh'
}, 2000)
return {
helloName,
name
}
},
})
</script>
<style scoped>
</style>
2. watch 监听
// 监听单参数的变化
watch(name, (newValue, oldValue) => {
console.log(newValue, oldValue, '----d')
})
// 监听对象的变化,第一个参数是函数
watch(() => person.age, (newValue, oldValue) => {
console.log(newValue, oldValue, 'zfb----d')
})
// 监听多个参数的变化 有第三个参数
watch(
() => [person.age, name],
// 数组形式 第一组是 新数值
// 数组形式 第二组是 旧数值
([ageNewValue, nameNewValue], [ageOldValue, nameOldValue]) => {
console.log(ageNewValue, ageOldValue, 'zfb----age')
console.log(nameNewValue, nameOldValue, 'zfb----name')
},
{
immediate: true
}
)
停止监听:
const stop = watch(
() => [person.age, name],
// 数组形式 第一组是 新数值
// 数组形式 第二组是 旧数值
([ageNewValue, nameNewValue], [ageOldValue, nameOldValue]) => {
console.log(ageNewValue, ageOldValue, 'zfb----age')
console.log(nameNewValue, nameOldValue, 'zfb----name')
},
{
immediate: true
}
)
setTimeout(() => {
stop()
}, 2000)