一, computed
当页面中有某些数据依赖其他数据进行变动的时候, 可以使用计算属性
- <p id="app"> {{fullName}} </p>
- <script>
- var vm = new vue({
- el: '#app',
- data: {
- firstName: 'Foo',
- lastName: 'Bar',
- },
- computed: {
- fullName: function () {
- return this.firstName + ' ' + this.lastName
- }
- }
- })
- </script>
需要注意的是, 就算在 data 中没有直接声明出要计算的变量, 也可以直接在 computed 中写入.
计算属性默认只有 getter, 可以在需要的时候自己设定 setter:
- ...
- computed: {
- fullName: {
- // getter
- get: function () {
- return this.firstName + ' ' + this.lastName
- },
- // setter
- set: function (newValue) {
- var names = newValue.split(' ')
- this.firstName = names[0]
- this.lastName = names[names.length - 1]
- }
- }
- }
这个时候在控制台直接运行 vm.fullName = 'bibi wang', 相应的 firstName 和 lastName 也会改变.
适用场景:
二, watch
watch 和 computed 很相似, watch 用于观察和监听页面上的 vue 实例, 当然在大部分情况下我们都会使用 computed, 但如果要在数据变化的同时进行异步操作或者是比较大的开销, 那么 watch 为最佳选择. watch 为一个对象, 键是需要观察的表达式, 值是对应回调函数. 值也可以是方法名, 或者包含选项的对象.
- var vm = new Vue({
- el: '#app',
- data: {
- firstName: 'Foo',
- lastName: 'Bar',
- fullName: 'Foo Bar'
- },
- watch: {
- firstName: function (val) {
- this.fullName = val + ' ' + this.lastName
- },
- lastName: function (val) {
- this.fullName = this.firstName + ' ' + val
- }
- }
- })
如果在 data 中没有相应的属性的话, 是不能 watch 的, 这点和 computed 不一样.
适用场景:
来源: http://www.bubuko.com/infodetail-3328438.html