toRef
content
The role of the toRef function: convert a property in the responsive object into a separate responsive data, and the converted value is associated with the previous one (the ref function can also be converted, but the value is not associated).
<template>
<div class="container">
<h2>{
{ name }}</h2>
<button @click="updateName">修改数据</button>
</div>
</template>
<script>
import { reactive, toRef } from 'vue'
export default {
name: 'App',
setup() {
const obj = reactive({
name: 'ifer',
age: 10
})
const name = toRef(obj, 'name')
const updateName = () => {
// 注意:需要使用 name.value 进行修改
name.value = 'xxx'
// 对 obj.name 的修改也会影响视图的变化,即值是关联的
// obj.name = 'xxx' // ok
}
return { name, updateName }
}
}
</script>
toRefs
content
The role of the toRefs function: convert all attributes in the responsive object into separate responsive data, and the converted value is associated with the previous one.
<template>
<div class="container">
<h2>{
{ name }} {
{ age }}</h2>
<button @click="updateName">修改数据</button>
</div>
</template>
<script>
import { reactive, toRefs } from 'vue'
export default {
name: 'App',
setup() {
const obj = reactive({
name: 'ifer',
age: 10
})
const updateName = () => {
obj.name = 'xxx'
obj.age = 18
}
return { ...toRefs(obj), updateName }
}
}
</script>