计算属性不需要再data中进行定义;
<template>
<div>{{fullName}}</div>
</template>
<script>
export default {
data() {
return {
firstName: "wang",
lastName: "wu"
}
},
computed: {
fullName: function () { // 监听data中的firstName和lastName值的变化, 得到新变量fullName,且fullName不需要再data中定义
return this.firstName + "-" + this.lastName;
}
}
}
</script>
<template>
<div>firstName: {{firstName}}</div>
<div>lastName: {{lastName}}</div>
<div>{{fullName}}</div>
<a @click="changeValue">更改</a>
</template>
<script>
export default {
data() {
return {
firstName: "wang",
lastName: "wu"
}
},
computed: {
fullName: { // 监听data中的firstName和lastName, 得到新变量fullName
get: function() {
return this.firstName + "-" + this.lastName;
} ,
// set方法作用:通过参数修改计算的依赖属性firstName和lastName值
set: function(newValue) {
this.firstName = newValue[0];
this.lastName = newValue[newValue.length-1];
}
}
},
methods: {
changeValue() {
// 调用计算属性的set方法,修改firstName和lastName
this.fullName="yyyyy";
}
}
}
</script>
<template>
<input type="text" v-model="question" />
</template>
<script>
export default {
data() {
return {
question: "",
answer: ""
}
},
watch: {
question: function () { // 监听question值的变化, 只要question发生变化,这个函数将会被执行;
this.answer="---------------------";
this.getAnswer();
}
},
methods: function() {
getAnswer() {
console.log("question属性值发生变化了。。。");
}
}
}
</script>
原文:https://www.cnblogs.com/zero-zm/p/12102668.html