vue3(reactive)vue2响应式区别
vue3实现添加删除对象的属性
vue3可以直接对对象进行添加和删除属性
<template>
<div>
<h2>{{ info.age }}</h2>
<h2 v-show="info.hobby">{{ info.hobby }}</h2>
<h2 v-show="info.sex">{{ info.sex }}</h2>
<div v-for="(item,index) in info.ability " :key='index' >{{item}}</div>
<button @click="addSex">添加性别</button>
<button @click="deletehobby">删除爱好</button>
<button @click="changeab">changeab</button>
</div>
</template>
<script>
import { reactive } from "vue";
export default {
setup() {
/***
* 作用:定义多个数据的响应式
* const proxy = reactive(obj)接受普通对象返回该普通对象的响应式代理对象
* 响应式转换深层次:会影响对象内部所有的嵌套的属性
* 内部基于es6的proxy实现,通过代理对象操作源对象内部数据都是响应式的
*/
let info = reactive({
age: 18,
hobby: "滑板",
ability: ["vue", "html", "csss", "react"],
});
function addSex() {
info.sex = "女";
}
function deletehobby() {
delete info.hobby;
}
function changeab() {
info.ability[0] = "javascript";
}
return {
info,
addSex,
deletehobby,
changeab,
};
},
};
</script>
vue2实现添加删除对象的属性
vue2需要this.$set(),this.$delete()
或者导入vue采用Vue.set()
import ‘Vue’ from vue
<template>
<div>
<h1>{{info.age}}</h1>
<h1>{{info.hobby}}</h1>
<h1 v-show="info.sex">{{info.sex}}</h1>
<button @click="setSex">添加性别</button>
<button @click="deletehobby">删除爱好</button>
<div v-for="(item,index) in info.ability " :key='index' >{{item}}</div>
<button @click="changeAb">changeAb</button>
</div>
</template>
<script>
export default {
data() {
return {
info: {
age:18,
hobby:'滑板',
ability: ["vue", "html", "csss", "react"],
}
}
},
methods: {
setSex() {
this.$set(this.info,'sex','女')
},
deletehobby(){
this.$delete(this.info,'hobby')
},
changeAb(){
// this.$set(this.info.ability,[0],'javascript')
this.info.ability.splice(0,1,'javascript')
}
},
}
</script>