计算属性
计算属性用于处理复杂的业务逻辑
计算属性具有依赖性,计算属性依赖 data中的初始值,只有当初始值改变的时候,计算属性才会再次计算
计算属性一般书写为一个函数,返回了一个值,这个值具有依赖性,只有依赖的那个值发生改变,他才会重新计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < meta http-equiv = "X-UA-Compatible" content = "ie=edge" > < title >表单输入绑定</ title > </ head > < body > < div id = "app" > {{ reverseMsg }}---- {{ reverseMsg }}-------- {{ reverseMsg }} //直接使用计算属性中的函数就是所要的数据 </ div > </ body > < script src = "vue.js" ></ script > //vue的js,不然使用不了vue语法 < script > const app = new Vue({ el: '#app', data: { msg: 'hello world' }, computed: { reverseMsg () { // 计算属性是一个函数,返回一个值,使用和data中的选项一样 console.log('computed') // 执行1次 --- 依赖性 return this.msg.split('').reverse().join(''); } } }) </ script > </ html > |
侦听属性(监听属性)
vue提供了检测数据变化的一个属性 watch 可以通过 newVal 获取变化之后的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < meta http-equiv = "X-UA-Compatible" content = "ie=edge" > < title >表单输入绑定</ title > </ head > < body > < div id = "app" > < input type = "text" v-model = "firstname" > + < input type = "text" v-model = "lastname" > = {{ fullname }} </ div > </ body > < script src = "vue.js" ></ script > < script > const app = new Vue({ el: '#app', data: { firstname: '李', lastname: '小龙', fullname: '李小龙' }, watch: { // 侦听属性 firstname (newVal, oldVal) { // newVal变化之后的值 this.fullname = newVal + this.lastname // 当改变 姓 的时候执行 }, lastname (newVal, oldVal) { this.fullname = this.firstname + newVal // 当改变 名字 的时候执行 } } }) </ script > </ html > |
以上就是vue中的计算属性和侦听属性的详细内容,更多关于vue 计算属性和侦听属性的资料请关注自学编程网其它相关文章!
- 本文固定链接: https://zxbcw.cn/post/199075/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)