Vue实例中的computed
属性是用于计算并返回一个新的值的,这个属性通常是与Vuex配合使用的,可通过Getter获取’mutations’中的状态,并计算状态后返回一个新的结果。而methods
属性则是用来定义方法的,通常用于响应事件或实现组件的业务逻辑等。
- 在Vue中,computed方法内的数据可以通过在methods方法内使用this关键字引用。因为computed属性的值是被缓存的,当computed属性所依赖的数据发生变化时,Vue负责重新计算并更新computed的结果。而methods方法则没有缓存的特性,每次调用都会执行一遍该方法。
以下是一个示例,展示如何在methods中使用computed方法内的数据:
<template>
<div>
<p>{{ fullName }}</p>
<button @click="greetWithName">Greet</button>
</div>
</template>
<script>
export default {
data() {
return {
firstName: "John",
lastName: "Doe"
};
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
},
methods: {
greetWithName() {
alert(`Hello, ${this.fullName}!`);
}
}
};
</script>