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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

LC蜗牛   2020-11-06 我要评论

计算属性

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

计算属性具有依赖性,计算属性依赖 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="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="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>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们