1.计算属性
(a)关键词:cumputed
<div id="app"> {{ strRender }} </div>
new Vue({
el:"#app",
data:{
str:"12345"
},
computed:{
strRender(){
this.str="54321"
}
}
})
(b)诞生原因
模板中放入太多的逻辑会让模板过重且难以维护,为了使得计算清晰明了,计算属性就诞生了
(c)小小技巧
1.依赖其他计算属性(计算属性函数相互间使用);
2.vue实例间的依赖(数据的想通相变);
<div id="app">
<p>原始字符串: {{ str }}</p>
<p>反转字符串: {{ renderStr }}</p>
</div>
var vm = new Vue({
el: '#app',
data: {
str: '丫头'
},
computed: {
renderStr: function () {
return this.str.split('').reverse().join('')
}
}
})
(d)比较methods
相同:1.效果相同,都是定义函数的地方;
不同:1.computed依赖实例的缓存变则变,methods只要重渲染函数总会重新调用;
(e)计算属性的 “设置器”:默认只有getter
var vm = new Vue({
el: '#app',
data: {
name: '丫头'
},
computed: {
site: {
get: function () {
return this.name
},
set: function (newValue) {
this.name = newValue
}
}
}
})
// 调用 setter, vm.name会被对应更新
vm.site = '新字段';
2.监听属性
(a)关键字:watch
<div id = "app">
<p>计数器: {{ counter }}</p>
<button @click = "num++">点我</button>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
num: 1
}
});
vm.$watch('num', function(nval, oval) {
alert('计数器值的变化 :' + oval + ' 变为 ' + nval + '!');
});
</script>
(b)使用场景
1.基础监听:60分以下不及格;60分-85分良好;85分以上优秀
<div id="app">
分数:<input type="number" v-model="achievement"><br>
提示:<span> {{infoMsg}} </span>
</div>
<script>
new Vue({
el:"#app",
data:{
achievement:"",
infoMsg:""
},
watch:{
achievement:function(newVal,oldVal){
if(newVal<60){
this.infoMsg="不及格"
}else if(newVal>60 && newVal<85){
this.infoMsg="良好"
}else{
this.infoMsg="优秀"
}
}
}
})
</script>
2.进阶监听:后台传值,且值藏在内部(非data的直接子数据)
注意:1.不可用箭头函数,因其this指向不是vue实例;2.新添属性deep,意为深度监听
<div id="app">
分数:<input type="number" v-model="info.achievement"><br>
提示:<span> {{infoMsg}} </span>
</div>
<script>
new Vue({
el:"#app",
data:{
info:{
achievement:"",
}
infoMsg:""
},
watch:{
info:{
handler:function(newVal,oldVal){
if(newVal.achievement<60){
this.infoMsg="不及格"
}else if(newVal.achievement>60 && newVal.achievement<85){
this.infoMsg="良好"
}else{
this.infoMsg="优秀"
}
},
deep:true
}
}
})
</script>
3.高级监听:后台传值,且内部数值对有好多
<div id="app">
分数:<input type="number" v-model="info.achievement"><br>
提示:<span> {{infoMsg}} </span>
</div>
<script>
new Vue({
el:"#app",
data:{
info:{
achievement:"",
age:"",
name:"",
city:""
}
infoMsg:""
},
computed:{
getAchievement:function(){
return this.info.achievement
}
},
watch:{
getAchievement:{
handler:function(newVal,oldVal){
if(newVal<60){
this.infoMsg="不及格"
}else if(newVal>60 && newVal<85){
this.infoMsg="良好"
}else{
this.infoMsg="优秀"
}
},
deep:true
}
}
})
</script>