get作用:当有人都去fullName时,get就会被调用,且返回的值作为fullName
get调用时机:
1.初次读取fullName时,
2.所依赖的数据会发生变化
set调用时机:
当fullName被修改时
<template> <div> <h1>一个人的信息</h1> 姓:<input type="text" v-model="firstName" /> <br> 名:<input type="text" v-model="lastName" /> <br> 全名:<span>{{fullName}}</span> <br> 修改:<input type="text" v-model="fullName" /> </div> </template>
<script> import {ref,computed} from 'vue' export default { setup(){ let firstName=ref('') let lastName=ref('') // let fullName=computed(()=>{ // return firstName.value+'-'+lastName.value // }) let fullName=computed({ get(){ return firstName.value+'-'+lastName.value }, set(value){ let nameArr=value.split('-') firstName.value=nameArr[0] lastName.value=nameArr[1] } }) return { firstName, lastName, fullName } } } </script>
只读不改可以简写
<script setup> import {ref,computed} from 'vue' let firstName=ref('') let lastName=ref('') let fullName=computed(()=>{ return firstName+'-'+lastName }) </script>
标签:firstName,lastName,value,let,计算,fullName,ref,属性 From: https://www.cnblogs.com/shuchenhao/p/16944550.html