<!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="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<!-- 基本使用 -->
<div id="app">
<!-- 一般调用:多次调用时略显麻烦 -->
<p>{{firstName + ' ' + lastName}}</p>
<p>{{firstName}} {{lastName}}</p>
<!-- 方法调用 -->
<p>{{getFullName()}}</p>
<!-- 计算属性:函数的方式定义,但当作属性使用 -->
<p>{{fullName}}</p>
</div>
<script>
const app = new Vue({
el:'#app',
data:{
firstName:'Lebron',
lastName:'James'
},
computed:{ // 计算属性
fullName:function(){
return this.firstName + ' ' + this.lastName;
}
},
methods:{
getFullName:function(){
return this.firstName + ' ' + this.lastName;
}
}
})
</script><hr>
<!-- 复杂操作 -->
<div id="app2">
<p>总价格:{{totalPrice}}</p>
</div>
<script>
const app2 = new Vue({
el:'#app2',
data:{
books:[
{id:001,name:"C++程序设计",price:100},
{id:002,name:"数据结构",price:120},
{id:003,name:'计算机操作系统',price:130}
]
},
computed:{ // 计算属性调用比methods调用性能更好,因为computed会有缓存
totalPrice:function(){
let result = 0;
for (let i = 0; i < this.books.length; i++){
result += this.books[i].price;
}
return result;
}
}
})
</script><hr>
<!-- setter和getter -->
<div id="app3">
<p>{{fullName}}</p>
</div>
<script>
const app3 = new Vue({
el:'#app3',
data:{
firstName:'Kobe',
lastName:'Bryant'
},
computed:{
fullName:{
set:function(newValue){
// 计算属性一般是不用set方法的,是只读属性
const names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[1];
alert('set被调用了');
},
get:function(){
return this.firstName + this.lastName;
}
}
}
})
</script><hr>
<!-- 计算属性与methods的对比 -->
<div id="app4">
<!-- 通过定义methods:函数调用四次 -->
<p>{{getFullName()}}</p>
<p>{{getFullName()}}</p>
<p>{{getFullName()}}</p>
<p>{{getFullName()}}</p>
<!-- 通过computed:函数调用一次 -->
<p>{{fullName}}</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
</div>
<script>
const app4 = new Vue({
el:'#app4',
data:{
firstName:'Kobe',
lastName:"Bryant"
},
methods:{
getFullName:function(){
console.log('执行methods');
return this.firstName + ' ' + this.lastName;
}
},
computed:{
fullName:function(){
console.log('执行computed');
return this.firstName + ' ' + this.lastName;
}
}
})
</script>
</body>
</html>
更多相关内容大家可以前往我的个人博客浏览:eyes++的个人空间