vue3.0 跟vue2.x使用方法差不多,说明都在备注里
<template>
<p>个人信息</p>
我的名字叫<input type="text" v-model="person.name" />,
今年<input type="text" v-model="person.age" />岁
<p>{{info}}</p>
</template>
<script>
// computed需要引入
import { reactive,computed} from "vue";
export default {
name: "Home",
setup() {
const person = reactive({
name: "张三",
age: 18,
});
// 带有返回值的函数
let info = computed( () => {
return person.name +'他' + person.age + '岁'
})
return {
person,
info
};
},
};
</script>
利用porxy特性,直接在person上追加属性,改成只读的
<template>
<p>个人信息</p>
我的名字叫<input type="text" v-model="person.name" />,
今年<input type="text" v-model="person.age" />岁
<p>{{person.info}}</p>
</template>
<script>
// computed需要引入
import { reactive,computed} from "vue";
export default {
name: "Home",
setup() {
const person = reactive({
name: "张三",
age: 18,
});
// 带有返回值的函数
person.info = computed( () => {
return person.name +'他' + person.age + '岁'
})
return {
person,
// info
};
},
};
</script>
读写都可以的,换个更直观的例子
<template>
<p>姓:<input v-model="person.fname" /></p>
<p>名:<input v-model="person.lname" /></p>
<p>全名:<input v-model="person.fullname" /></p>
</template>
<script>
// computed需要引入
import { reactive, computed } from "vue";
export default {
name: "Home",
setup() {
const person = reactive({
fname: "张",
lname: "三",
});
person.fullname = computed({
get() {
return person.fname + "-" + person.lname;
},
set(val) {
const newName = val.split("-");
console.log("newName", newName);
person.fname = newName[0];
person.lname = newName[1];
},
});
return {
person,
};
},
};
</script>