computed代表计算属性,本质上是通过计算之后得到的一个变量
引进来
import { defineComponent,ref, computed} from "vue";
<template> <div> <nav-header></nav-header> <nav-main></nav-main> <nav-footer></nav-footer> <div>{{ num1 }}---{{ num2 }}</div> <div>两个数的和{{ addNum }}</div> </div> </template> <script> import NavHeader from "@/components/navHeader/NavHeader.vue"; import NavMain from "@/components/navMain/NavMain.vue"; import NavFooter from "@/components/navFooter/NavFooter.vue"; //reactive定义对象类型的数据 import { defineComponent, ref, computed } from "vue"; export default defineComponent({ name: "Home", props: {}, components: { NavHeader, NavMain, NavFooter, }, setup() { let num1 = ref(10); let num2 = ref(20); let addNum = computed(() => { return num1.value + num2.value; }); return { num1, num2, addNum, }; }, }); </script> <style> </style>
改变两个数的值
<button @click="add">add</button>
let add=()=>{ num1.value++ num2.value++ }
return { add };
运行结果