源码
App.vue
<template>
<h1>我是Vue2写的效果</h1>
<h2 v-show="person.name">姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}}</h2>
<h2 v-show="person.sex">年龄:{{person.sex}}</h2>
<button @click="addSex">添加一个sex属性</button>
<button @click="delName">删除一个name属性</button>
<button @click="updateHobby">修改第一个属性</button>
</template>
<script>
//引入 ref()
//import {reactive, ref} from 'vue'
export default {
name: 'App',
data() {
return {
person : {
name: '张三',
age: 18,
hobby:['学习','吃饭']
}
}
},
methods:{
addSex(){
console.log('添加前 this.person.sex=',this.person.sex)
//this.person.sex = '女' //添加一个属性,
console.log('添加后 this.person.sex=',this.person.sex)
//在之前的 Vue2 中,上面的方法是没有办法添加属性,替换的方法:
//在不引入 Vue 的时候:
this.$set(this.person,'sex','女')
//引入 Vue的时候:
//Vue.set(this.person,'sex','女')
},
delName(){
console.log("删除前 this.person.name=",this.person.name)
delete this.person.name
console.log("删除后 this.person.name=",this.person.name)
//在之前的 Vue2 中,上面的方法是没有办法删除其属性的,替换方法:
//在不引入 Vue 的时候:
//this.$delete(this.person,'name')
//引入 Vue的时候:
//Vue.delete(this.person,'name')
},
updateHobby() {
//this.person.hobby[0] = '逛街'
//在之前的 Vue2 中,上面的方法是没有办法修改其属性的,替换方法:
//vue.js:2463 Uncaught TypeError: this.$set is not a function
//this.$set(this.person.hobby,0,'逛街')
this.person.hobby.splice(0,1,'冥想')
}
}
}
</script>
