您的位置:首页技术文章
文章详情页

vue中的计算属性和侦听属性

浏览:71日期:2022-11-05 13:16:21

计算属性

计算属性用于处理复杂的业务逻辑

计算属性具有依赖性,计算属性依赖 data中的初始值,只有当初始值改变的时候,计算属性才会再次计算

计算属性一般书写为一个函数,返回了一个值,这个值具有依赖性,只有依赖的那个值发生改变,他才会重新计算

<!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='https://www.haobala.com/bcjs/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 获取变化之后的值

<!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='https://www.haobala.com/bcjs/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 计算属性和侦听属性的资料请关注好吧啦网其它相关文章!

标签: Vue
相关文章: