demo.html
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-html="http://www.w3.org/1999/xhtml"
xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Vue Demo</title>
<!--自选版本-->
<!--<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>-->
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生产环境版本,优化了尺寸和速度 -->
<!--<script src="https://cdn.jsdelivr.net/npm/vue"></script>-->
</head>
<body>
<div id="app">
<div>
<h3>computed 计算属性举例</h3>
<div>
<p>
method在使用时会执行所有方法;<br>
computed在使用时只执行相关的操作;<br>
computed属性比method更节省资源和性能;在需要复杂计算或耗时较多的操作时使用。<br>
</p>
</div> <hr> <div>
<h3>method方式实现</h3>
<button v-on:click="a++" type="button">
ADD To A
</button> <button v-on:click="b++" type="button">
ADD To B
</button> <p>A : {{a}}</p>
<p>B : {{b}}</p>
<p>Age + A = {{ageAddA()}}</p>
<p>Age + B = {{ageAddB()}}</p>
</div> <hr> <div>
<h3>computed 计算属性方式实现</h3>
<button v-on:click="c++" type="button">
ADD To C
</button> <button v-on:click="d++" type="button">
ADD To D
</button> <p>C : {{c}}</p>
<p>D : {{d}}</p>
<p>Age + C = {{ageAddC}}</p>
<p>Age + D = {{ageAddD}}</p>
</div>
</div> </div>
<script src="app.js"></script> </body>
</html>
app.js
var app = new Vue({
el: '#app',
data: {
a: 0,
b: 0,
age: 20,
c: 0,
d: 0, },
methods: {
ageAddA: function () {
console.log("A:" + this.a);
return this.age + this.a;
},
ageAddB: function () {
console.log("B:" + this.b);
return this.age + this.b;
}
}, computed:{
ageAddC: function () {
console.log("C:" + this.c);
return this.age + this.c;
},
ageAddD: function () {
console.log("D:" + this.d);
return this.age + this.d;
}
}
})
截图: