Vue3中的计算函数有两种写法:简写和完整写法。下面一一介绍下。

计算函数的简写

  • main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
  • App.vue
<template>
  <Demo/>
</template>

<script>
import Demo from './components/Demo.vue'

export default {
  name: 'App',
  components: {
    Demo
  }
}
</script>
  • Demo.vue
<template>
  姓:<input type="text" v-model="person.firstName">
  <br>
  名:<input type="text" v-model="person.lastName">
  <div>全名:{{fullName}}</div>
</template>

<script>
import {reactive,computed} from "vue";
export default {
  name: 'Demo',
  setup(){
    let person = reactive({
      firstName:"张",
      lastName:"三"
    })

    let fullName = computed(() => {
      return person.firstName + "-" + person.lastName;
    })

    return {
      person,
      fullName
    }
  }
}
</script>
  • 启动应用,测试效果
    在这里插入图片描述

其实,fullName也是应该是person的属性,所以修改Demo.vue,稍稍改进下。

<template>
  姓:<input type="text" v-model="person.firstName">
  <br>
  名:<input type="text" v-model="person.lastName">
  <div>全名:{{person.fullName}}</div>
</template>

<script>
import {reactive,computed} from "vue";
export default {
  name: 'Demo',
  setup(){
    let person = reactive({
      firstName:"张",
      lastName:"三"
    })

    person.fullName = computed(() => {
      return person.firstName + "-" + person.lastName;
    })

    return {
      person
    }
  }
}
</script>

在这里插入图片描述
在这里插入图片描述

计算函数的完整写法

  • main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
  • App.vue
<template>
  <Demo/>
</template>

<script>
import Demo from './components/Demo.vue'

export default {
  name: 'App',
  components: {
    Demo
  }
}
</script>
  • Demo.vue
<template>
  姓:<input type="text" v-model="person.firstName">
  <br>
  名:<input type="text" v-model="person.lastName">
  <br>
  姓名:<input type="text" v-model="person.fullName">
</template>

<script>
import {reactive,computed} from "vue";
export default {
  name: 'Demo',
  setup(){
    let person = reactive({
      firstName:"张",
      lastName:"三"
    })

    person.fullName = computed({
      get(){
        return person.firstName + "-" + person.lastName;
      },
      set(value){
        const tempArr = value.split("-");
        person.firstName = tempArr[0];
        person.lastName = tempArr[1];
      }
    })

    return {
      person
    }
  }
}
</script>

在这里插入图片描述

  • 启动应用,测试效果
    在这里插入图片描述
Logo

前往低代码交流专区

更多推荐