1.vue 中的 this.$options.data()获取的不是初始值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<div>{{text}}</div>
<button @click="sum()">sum</button>
<button @click="reset">reset</button>
</div>
</body>
<script src="js/index1.js"></script>
</html>
var app = new Vue({
el: '#app',
data: {
text:'aaa'
},
methods:{
reset(){
console.log(this.$options.data())
Object.assign(this.$data, this.$options.data())
},
sum(){
this.text = 'bbb'
}
}
})
点击reset按钮并不能把vue的data重置,通过console看到this.$options.data()获取的值还是bbb,如何才能重置vue的data
其实你写法并没有错,只是当你实例Vue的时候data是一个对象,而不是一个函数。因为对象是引用类型,this.$options.data()返回的值和this.$data 都指向 data 的引用地址 所以当你改变this.data的时候,这两个值都会改变。如果你把data改成 data(){return {text:'aaa'}} 返回一个新对象 。this.$options.data()返回的值和this.$data 都指向不同的地址。这个时候改变this.data时 this.$options.data()返回值就不会改变。