目录
(1)比如写一个实时更新的姓名系统
代码;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="../vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="root">
姓: <input type="text" v-model="firstName" /><br />
<br />
名: <input type="text" v-model="lastName" /><br />
<br />
全名:<span>{{fullName}}</span>
</div>
<script>
Vue.config.productionTip = false; //阻止 vue在启动时生成生产提示。
new Vue({
el: "#root",
data: {
firstName: "刘",
lastName: "家奕",
},
computed: {
fullName: {
get() {
return this.firstName + "-" + this.lastName;
},
},
},
});
</script>
</body>
</html>
(2)随便更改姓或者名,姓名也会随着一起变换~
(3)那么这个 姓名之间的连接符 是有什么用吗 ?
给Vue一个接收vm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="../vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="root">
姓: <input type="text" v-model="firstName" /><br />
<br />
名: <input type="text" v-model="lastName" /><br />
<br />
全名:<span>{{fullName}}</span>
</div>
<script>
Vue.config.productionTip = false; //阻止 vue在启动时生成生产提示。
const vm = new Vue({
el: "#root",
data: {
firstName: "刘",
lastName: "家奕",
},
computed: {
fullName: {
get() {
return this.firstName + "-" + this.lastName;
},
set(value) {
console.log("set", value);
const arr = value.split("-"); //分隔开符
this.firstName = arr[0];
this.lastName = arr[1];
},
},
},
});
</script>
</body>
</html>
写一个和get()同级的set():
效果就是改变全名时可以同时改变姓和名:
并且给一个反馈:
(4)简写形式(只读不改,无set())
<script>
Vue.config.productionTip = false; //阻止 vue在启动时生成生产提示。
const vm = new Vue({
el: "#root",
data: {
firstName: "刘",
lastName: "家奕",
},
computed: {
fullName() {
return this.firstName + "-" + this.lastName;
},
},
});
</script>
只变了这个: