Vue 2.x – 计算属性

定义

要用的属性不存在,要通过已有属性计算得来。

原理

底层借助了Objcet.defineproperty方法提供的getter和setter。

示例

<div id="root">
        姓:<input type="text" v-model="firstName"><br>
        名:<input type="text" v-model="lastName"><br>
        全名:<span>{{fullName}}</span>
    </div>

    <script>
        const vm = new Vue({
            el: '#root',
            data: {
                firstName: "张",
                lastName: '三'
            },
            // 计算属性写在computed中
            computed: {
                fullName: {
                    get() {
                        console.log("get");
                        // console.log(this); // 此处的this是vm
                        return this.firstName + '-' + this.lastName
                    },
                    set(value) {
                        console.log('set', value);
                        const arr = value.split('-')
                        this.firstName = arr[0]
                        this.lastName = arr[1]
                    }
                }
            }
        })
    </script>

 

get函数什么时候执行?

(1).初次读取时会执行一次。
(2).当依赖的数据发生改变时会被再次调用。

优势

与methods实现相比,内部有缓存机制(复用),效率更高,调试方便。

备注

1.计算属性最终会出现在vm上,直接读取使用即可。
2.如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。

简写

<script type="text/javascript">
		const vm = new Vue({
			el:'#root',
			data:{
				firstName:'张',
				lastName:'三',
			},
			computed:{
				//完整写法
				/* fullName:{
					get(){
						console.log('get被调用了')
						return this.firstName + '-' + this.lastName
					},
					set(value){
						console.log('set',value)
						const arr = value.split('-')
						this.firstName = arr[0]
						this.lastName = arr[1]
					}
				} */
				//简写
				fullName(){
					console.log('get被调用了')
					return this.firstName + '-' + this.lastName
				}
			}
		})
	</script>

 

 

版权声明:
作者:Ne-21
链接:https://blog.gocos.cn/archives/102.html
来源:云淡风轻
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Vue 2.x – 计算属性
定义 要用的属性不存在,要通过已有属性计算得来。 原理 底层借助了Objcet.defineproperty方法提供的getter和setter。 示例 <div id="root"> ……
<<上一篇
下一篇>>