自学内容网 自学内容网

Vue3 中使用 toRefs的方法

首先画出模板

<template>
    <div class="person">
        <h2>姓名:{{ person.name }}</h2>
        <h2>年龄:{{ person.age }}</h2>
        <button @click="showTel">查看联系方式</button>
        <button @click="changeName">修改名字</button>
        <button @click="chanegAge">修改年龄</button>
    </div>
    
</template>

定义响应式对象

<script lang="ts" setup name="PersonToRefs">
import { ref, reactive,toRefs } from 'vue'

const person = reactive({
    name: "zhangsan",
    age: 18,
    tel :123456789
})

// 现在将数据进行解析出来
// const {name,age} = person //此时的name,age并不是响应式的
const {name,age} = toRefs(person) //此时的name,age是响应式的,但是其值是响应式的,但是其值是结构成ref(响应式)对象的数据


function changeName(){
    person.name = person.name + '~'
    console.log("name",name.value);
    console.log("person.name",person.name);
}

function chanegAge(){
    person.age = person.age + 1
    console.log("age",age.value);
    console.log("person.age",person.age);
}

function showTel(){
    alert(person.tel)
}

</script>

样式:

<style scoped>
.person {
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px
}
</style>

小结:

当我们使用,reactive定义响应式对象的时候,使用let{name,age} = person 解析对象后,

其name,age并不是响应式的,因此我们需要使用,toRefs属性,将其转化为响应式的

并且,使用toRefs转化后的name,age其变成了,与person相关联的Ref响应式数据

当只需要某个对象的单个属性的时候,可以使用toRef

const roRefName = toRef(person,'name')

console.log(roRefName.value);


原文地址:https://blog.csdn.net/qq_58341172/article/details/142876682

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!