VUE入门-计算属性以及数据监听
By:Roy.LiuLast updated:2020-09-16
vue计算属性,打个比方就如同计算器的两个加数,改变任何一个,和都会自动计算。在进行数据运算时非常方便。
vue的监听,就是监听某一个属性的值是否满足某个条件,然后触发某个响应。
如果用传统的方法,通常是在 输入框的 onblur方法中去处理一些逻辑,但如果用了VUE,就只需要个方法,不需要在每个元素上绑定onblur等方法。下面的例子计算了count的和,另外在 ProductName等于 product-B 的时候,会触发watch的逻辑.
<!DOCTYPE html> < html > < head > < script src = "vue.js" ></ script > </ head > < body > < div id = "app" ></ div > < script > new Vue({ el:"#app", template:` < div > < div > Product Name: < input type = "text" v-model = "name" /> < br /> Count1: < input type = "text" v-model = "count1" /> < br /> Count2: < input type = "text" v-model = "count2" /> Total Count: {{totalCount}} < br /> < div v-show = "showb" >Show this zone when product-B is ready</ div > </ div > </ div > `, data:function(){ return { name:"product-A", count1:2, count2:3, showb:false } }, computed:{ totalCount:function() { return Number(this.count1) + Number(this.count2); } }, watch:{ name:{ handler:function(newVal, oldVal){ if (newVal == "product-B") { alert("product-B is ready"); this.showb=true; } else { this.showb=false; } } } } }) </ script > </ body > </ html > |
From:一号门
Previous:VUE入门-过滤器的使用
Next:VUE入门-组件化开发
COMMENTS