Skip to content

Vue教程08:Computed计算属性、Watch监听属性 #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

Vue教程08:Computed计算属性、Watch监听属性 #9

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

Computed计算属性

代码示例:/lesson08/01. Computed计算属性.html

计算属性类似于方法,用于输出数据的计算结果,在数据变化时,它会同步更新,计算属性不可与data中的属性重名。
相对于方法,它的优势是当它的依赖变化时,才会重新进行计算,也就是说它拥有缓存,而方法在每次render的时候都会计算,因此computed的性能较高。

计算属性除了设置为方法外,还可以用作对象,通过get、set方法进行读写操作。

计算属性还可以当做普通属性使用,通过v-model绑定在input上,而方法无法做到。

JavaScript:

let vm = new Vue({
  el: '#app',
  data: {
    a: 12,
    b: 33,
    familyName: '张',
    name: '三'
  },
  computed: {
    sum() {
      return this.a + this.b
    },
    fullName: {
      get() {
        return this.familyName + this.name
      },
      set(value) {
        this.familyName = value[0]
        this.name = value.substring(1)
      },
    }
  },
})

HTML:

<div id="app">
  <div>
    {{a}} + {{b}} = {{sum}}
    姓:<input type="text" v-model="familyName">
    名:<input type="text" v-model="name">
    姓名:<input type="text" v-model="fullName">
  </div>
</div>

Watch监听属性

代码示例:/lesson08/02. Watch监听属性.html

Watch监听属性可以监听数据的变化,不止可以监听某个变量,还可以监听对象中的属性,数组中的item。

let vm = new Vue({
  el: '#app',
  data: {
    name: 'lee',
    userInfo: {
      name: 'lee',
      age: 18
    },
    users: [
      'lee',
      'chen',
      'john'
    ]
  },
  watch: {
    name(value) {
      console.log(`name改变为${value}`)
    },
    // userInfo的属性修改不会触发该监听
    userInfo(value) {
      console.log('userInfo已改变', value)
    },
    // 可以监听对象的属性变化
    'userInfo.name': function(value) {
      console.log(`userInfo.name改变为${value}`)
    },
    // 可以监听数组中的某一项
    'users.1': function (value) {
      console.log(`users[1]改变为${value}`)
    },
    // 修改users[1]的值同时也会触发对数组的监听
    users(value) {
      console.log(`users改变为${value}`)
    },
  }
})

HTML:

<div id="app">
  <div>
    <input type="text" v-model="name">
    <input type="text" v-model="userInfo.name">
    <input type="text" v-model="users[1]">
  </div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant