computed 基本使用 如果数据需要有复杂的计算,则可以在Vue实例中定义计算属性,再交由mustache进行渲染。 computed内部其实是通过getttr实现的,所以不用加括号即可完成其下方
computed
<div id="app">
书籍的总价格是:{{totalPrice}}
</div>
<script src="./vue.js"></script>
<script>
const app = new Vue({
el: "#app",data: {
books: {
"Vue实战": 128,"JavaScrip入门": 99,"HTML5初识": 87,"CSS3": 68,}
},computed: {
totalPrice() {
return Object.values(this.books).reduce((pre,cur) => {
return pre + cur;
},0)
}
}
})
</script>
methods
<body>
<div id="app">
书籍的总价格是:{{totalPrice()}}
</div>
<script src="./vue.js"></script>
<script>
const app = new Vue({
el: "#app",computed: {
},methods:{
totalPrice() {
return Object.values(this.books).reduce((pre,0)
}
}
})
</script>
</body>
差异区别
<body>
<div id="app">
{{computedAdd}}
{{computedAdd}}
{{computedAdd}}
<hr>
{{methodsAdd()}}
{{methodsAdd()}}
{{methodsAdd()}}
<button type="button">查看各执行几次</button>
</div>
<script src="./vue.js"></script>
<script>
let computedCount = 0;
let methodsCount = 0;
const app = new Vue({
el: "#app",data: {
num1: 100,num2: 200,},computed: {
computedAdd() {
computedCount++;
return this.num1 + this.num2;
}
},methods: {
methodsAdd() {
methodsCount++;
return this.num1 + this.num2;
}
}
})
document.querySelector("button").addEventListener("click",() => {
console.log(`computed调用了${computedCount}次`);
console.log(`methods调用了${methodsCount}次`);
},)
</script>
</body>