1.计算属性get方法:
计算属性(computed)和Methods区别:
计算属性(computed)适合:有缓存 不能在属性名后加() eg: {{reverse}}
methods:无缓存 加() eg: {{reverseStr()}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<p>初始值:{{name}}</p>
<p>翻转值:{{name.split('').reverse().join('')}}</p>
<p>函数调用:{{reverseStr()}}</p>
<p>计算属性:{{reverse}}</p>
</div>
<script src="../js/vue.min.js"></script>
<script>
new Vue({
el:'#app',
data:{
name:'Rose Jack'
},
methods:{
reverseStr(){
return this.name.split('').reverse().join('')
}
},
//计算选项
computed:{
//get方法
reverse(){
return this.name.split('').reverse().join('')
}
}
})
</script>
</body>
</html>
2.计算属性setter方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<p>{{fullName}}</p>
<button @click="deal()">调用计算属性的setter方法</button>
</div>
<script src="../js/vue.min.js"></script>
<script>
new Vue({
el:'#app',
data:{
firstName:'zhang',
lastName:'sanfeng'
},
methods:{
deal(){
this.fullName = 'Token Lily';//调用fullName的set方法
}
},
computed:{
//get
/*fullName(){
return this.firstName+' '+this.lastName;
}*/
fullName:{
//get方法
get(){
return this.firstName + ' ' + this.lastName;
},
//set方法
set(str){
let nameArr = str.split(' ');
this.firstName = nameArr[0];
this.lastName = nameArr[1];
}
}
}
})
</script>
</body>
</html>