014、Vue3+TypeScript基础,computed计算属性中使用get和set方法来读取和修改

01、App.vue代码如下:

复制代码
<template>
  <div class="app">
    <h2>{{ title }}</h2>
    <!--    使用了ref来获取子组件的属性-->
    <Person/>
  </div>
</template>

<script lang="ts" setup name="App">
// JS或TS
import Person from './view/Person.vue'
import {ref} from 'vue'

let title = ref('好好学习,天天向上')

</script>

<!--样式 scoped表示仅本单元有效-->
<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>
复制代码

02、Person.vue代码如下:

复制代码
<template>
  <div class="person">
    姓:<input type="text" v-model="firstName"/><br>
    名:<input type="text" v-model="lastName"/><br>
    <button @click="changeFullName">改变全名</button>
    <br>
    全名<span>{{ fullName }}</span><br>
    全名<span>{{ fullName }}</span><br>
  </div>
</template>

<script lang="ts" name="Person001" setup>
import {computed, ref} from 'vue'

let firstName = ref('')
let lastName = ref('')
//计算属性,计算属性的结果会被缓存,只有当依赖发生改变时,计算属性才会重新计算。
//通过computed()方法创建一个计算属性,get方法返回计算结果,set方法用于设置计算属性的值。
let fullName = computed({
  // get方法
  get() {
    console.log('get被调用了');
    return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1)
        + '_' + lastName.value;
  },
  // set方法
  set(val) {
    console.log('set被调用了');
    let arr = val.split('_');
    firstName.value = arr[0];
    lastName.value = arr[1];
  }
})

// 按钮点击事件
function changeFullName() {
  fullName.value = 'tian_pan'
}
</script>
<style scoped>
.person {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;

  button {
    margin: 0 5px;
  }
}
</style>
复制代码

03、效果如下:

 

posted @   像一棵海草海草海草  阅读(297)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示