ref()
基本数据类型
直接监听
const refData = ref(null)
watch(refData, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
引用数据类型
- 需要deep
需添加 deep:true 才能监听值改变,但newValue与 oldValue值相同
const refData = ref([1, 2, 3])
watch(
refData,
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ deep: true }
)
//newValue:Proxy(Array) {0: 1, 1: 2, 2: 3, 3: 4}
//oldValue:Proxy(Array) {0: 1, 1: 2, 2: 3, 3: 4}
//修改refData
const changeData = () => {
refData.value.push(4)
}
- 深拷贝并写作getter形式
通过深拷贝(以扩展运算符为例),解决newValue与 oldValue值相同问题
const refData = ref([1, 2, 3])
watch(
() => [...refData.value],
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ deep: true }
)
//newValue:[1, 2, 3, 4]
//oldValue:[1, 2, 3]
//修改refData
const changeData = () => {
refData.value.push(4)
}
reactive()
- 无需加deep,默认deep:true
能监听值改变,但newValue与 oldValue值相同
const reactiveData = reactive({ content: 'reactiveContent' })
watch(reactiveData, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
//newValue:Proxy(Object) {content: 'reactiveContentChange'}
//oldValue:Proxy(Object) {content: 'reactiveContentChange'}
//修改reactiveData
const changeData = () => {
reactiveData.content = 'reactiveContentChange'
}
- 解决值相同问题
Object:直接监听具体值而非整个对象,并写作getter形式
const reactiveData = reactive({ content: 'reactiveContent' })
watch(
() => reactiveData.content,
(newValue, oldValue) => {
console.log(newValue, oldValue)
}
)
//newValue:reactiveContentChange
//oldValue:reactiveContent
//修改reactiveData
const changeData = () => {
reactiveData.content = 'reactiveContentChange'
}
Array:深拷贝,并写作getter形式
const reactiveData = reactive([1, 2, 3])
watch(
() => [...reactiveData],
(newValue, oldValue) => {
console.log( newValue, oldValue)
}
)
//newValue:[1, 2, 3, 4]
//oldValue:[1, 2, 3]
//修改refData
const changeData = () => {
reactiveData.push(4)
}
注:扩展运算符只对一层的数组或对象是深拷贝,多层的不要用这深拷贝!!!