toRef函数是Vue 3中的一个新特性,它可以将一个响应式对象的属性转换成一个普通的引用,能够在我们不需要监听这个属性时使用。下面是toRef的使用场景和代码示例:
- 在setup函数中将props属性转换成一个引用,方便在逻辑中使用:
import { toRef } from 'vue'
export default {
props: {
msg: String
},
setup(props) {
const msgRef = toRef(props, 'msg')
return {
msgRef
}
}
}
- 将一个响应式对象中的属性转换成一个普通的引用,可以提高性能:
import { reactive, toRef } from 'vue'
const reactiveObj = reactive({
name: 'vue',
age: 3
})
// 转换成普通的引用
const nameRef = toRef(reactiveObj, 'name')
const ageRef = toRef(reactiveObj, 'age')
- 在computed函数中使用toRef,可以方便地监控一个响应式对象中的属性:
import { reactive, toRef, computed } from 'vue'
const reactiveObj = reactive({
name: 'vue',
age: 3
})
const nameRef = toRef(reactiveObj, 'name')
const ageRef = toRef(reactiveObj, 'age')
const fullName = computed(() => {
return `${nameRef.value} ${ageRef.value}`
})
- 在watch函数中使用toRef,可以监控一个响应式对象中的属性,只有在该属性发生变化时才会触发回调函数:
import { reactive, toRef, watch } from 'vue'
const reactiveObj = reactive({
name: 'vue',
age: 3
})
const nameRef = toRef(reactiveObj, 'name')
const ageRef = toRef(reactiveObj, 'age')
watch(nameRef, (newValue, oldValue) => {
console.log('name changed', newValue, oldValue)
})