1,什么时候使用$set

set为解决双向绑定失效而生,只需要关注什么时候双向绑定失效就可以了。

2,Vue.set 和 this.$set

 this.$set 实例方法,该方法是全局方法 Vue.set 的一个别名

3,$set 用法

数组:

this.$set(Array, index, newValue)

对象:

this.$set(Object, key, value)

4,实例

data中未定义,手动给form添加age属性,并且点击按钮进行自增。

如果使用 this.form.age = 10 这种方式,不能进行添加和自增,数据无法响应式。

使用 this.$set方式实现响应式

<template>
	<div>
		<h1> {{ form }} </h1>   <!--{name:'xxx'}/ {name:'xxx',age:10}-->
		<button @click="add">添加</button>
	</div>
</template>
<script>
export default{
	data(){
		return{
			form:{
				name: 'xxx',
			}
		}
	}
	methods:{
		add(){
			if(!this.form.age){
				this.$set(this.form, age, 10) // 成功
				
				// Vue2中监听不到动态给对象添加的属性的
				// this.form.age = 10   // 失败无法添加,更无法自增
			} else {
				this.form.age++
			}
		}
	}
}
</script>

作用

如果是一个对象,我们可以给他动态增添一些属性,并且保证这些属性是个响应式的!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐