vue3中的计算属性computed

<template>
  <div>
    <h1>一个人的信息</h1>
    姓:<input v-model="person.firstName" />
    名:<input v-model="person.lastName"/>
    全名:{{ person.fullName }}
  </div>
</template>
import { reactive, computed } from "vue";
export default {
  name: "Demo",
  setup(props, context) {
    let person = reactive({
      firstName: "张",
      lastName: "三",
    });
    //计算属性(第一种,不考虑计算属性被修改)
    // person.fullName = computed(() => {
    //   return person.firstName + person.lastName;
    // });


    //第二种完整写法,考虑读和写
    person.fullName = computed(() => {
      get: () => { 
        return person.firstName + '-' + person.lastName;
      }
      set: (val) => {
        const nameArr = val.split('-')
        person.firstName = nameArr[0]
        person.lastName = nameArr[1]
      }
    })
    return {
      person,
    };
  },
};
</script>

 

posted @ 2021-10-09 09:42  赵永强  阅读(3427)  评论(0编辑  收藏  举报