1、主要代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-hellovuejs</title>
<style>
</style>
</head>
<body>
<div id ="app">
<!-- (1)老方法 -->
<h2>{{firstname+' '+ lastname}}</h2>
<h2>{{firstname}} {{lastname}}</h2>
<!-- (2)methods -->
<h2>{{getFullname()}}</h2>
<!-- (3)computed -->
<h2>{{fullname}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
//let(变量) /const(常亮)
const chen1 = new Vue({
el: '#app', //用于挂载要管理的元素
data:{//定义数据
message:'你好啊,helloword',
firstname: 'chen',
lastname: 'niu'
},
methods:{
getFullname(){
return this.firstname+' '+ this.lastname
}
},
computed:{
fullname(){
return this.firstname+' '+ this.lastname
}
}
})
</script>
</body>
效果如下
2、computed计算总价格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-hellovuejs</title>
<style>
</style>
</head>
<body>
<div id ="app">
<!-- computed -->
<h2>{{totalprice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
//let(变量) /const(常亮)
const chen1 = new Vue({
el: '#app', //用于挂载要管理的元素
data:{//定义数据
books:[
{id:110,name:'Unix编程艺术',price:122},
{id:111,name:'代码大全',price:113},
{id:112,name:'深入理解计算机原理',price:88},
{id:113,name:'现代操作系统',price:66}
]
},
computed:{
totalprice:function(){
let result = 0;
for(let i=0;i< this.books.length;i++){
result +=this.books[i].price;
}
//下面是高级用法
// for(let book of this.books)
// {
// result +=book.price;
// }
return result
}
}
})
</script>
</body>
3、compute的setter和getter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-hellovuejs</title>
<style>
</style>
</head>
<body>
<div id ="app">
<!-- computed -->
<h2>{{fullname}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
//let(变量) /const(常亮)
const chen1 = new Vue({
el: '#app', //用于挂载要管理的元素
data:{//定义数据
message:'你好啊,helloword',
firstname: 'chen',
lastname: 'niu'
},
computed:{
fullname: {
set:function(newValue){
console.log('-----',newValue);
const names = newValue.split(' ');
this.firstname = names[0];
this.lastname = names[1];
},
get:function(){
return this.firstname+' '+ this.lastname;
}
}
}
})
</script>
</body>
4、computed和methods相比,性能更优,有缓存
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-hellovuejs</title>
<style>
</style>
</head>
<body>
<div id ="app">
<!-- (1)老方法 不推荐-->
<h2>{{firstname+' '+ lastname}}</h2>
<h2>{{firstname}} {{lastname}}</h2>
<!-- (2)methods -->
<h2>{{getFullname()}}</h2>
<h2>{{getFullname()}}</h2>
<h2>{{getFullname()}}</h2>
<h2>{{getFullname()}}</h2>
<!-- (3)computed -->
<h2>{{fullname}}</h2>
<h2>{{fullname}}</h2>
<h2>{{fullname}}</h2>
<h2>{{fullname}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
//let(变量) /const(常亮)
const chen1 = new Vue({
el: '#app', //用于挂载要管理的元素
data:{//定义数据
message:'你好啊,helloword',
firstname: 'chen',
lastname: 'niu'
},
methods:{
getFullname(){
console.log('---methods--');
return this.firstname+' '+ this.lastname
}
},
computed:{
fullname(){
console.log('---computed--');
return this.firstname+' '+ this.lastname
}
}
})
</script>
</body>