官网解释:当一个组件被定义,data 必须申明为返回一个初始数据对象的函数,因为组件可能被用来创立多个实例。
如果 data 依然是一个纯正的对象,则所有的实例将共享援用同一个数据对象!通过提供 data 函数,每次创立一个新实例后,咱们可能调用 data 函数,从而返回初始数据的一个全新正本数据对象。
我看到这个问题的时候是我面试的时候一个面试官问我的,过后懵了,素来没有想过为什么,只晓得代码须要这么写。最近有空再来理解一下这部分的原理内容。有两个我比拟喜爱答复
1.是为了在反复创立实例的时候防止共享同一数据造成的数据净化
2.写函数的起因是为了保障这个对象是独立的,如果能够保障对象是惟一的,也能够不写函数间接写对象。
其实归根结底就是为了防止数据净化。
咱们想要解决这个问题就不得不说原型链和this。
看个例子
person1和person2是Person的援用,所以当person2扭转数据是实际上更改的是Person的的数据。既然Person的数据扭转了,所以Person的援用person1也会被扭转
function Person(){ } Person.prototype.datas={ a:"c", f:'h' } var person1 = new Person() var person2 = new Person() person2.datas.a="wewew" console.log(person2) console.log(person1)
我之前始终有一个疑难既然person1和person2都是Person的援用为什么放在对象外面会造成数据净化然而放在办法里就不会造成数据净化了呢?首先要晓得一句话:this的指向在函数定义的时候是确定不了的,只有在函数执行的时候能力确定this到底指向谁
实际上this指向调用它的对象。又有一个疑难了,明明指向的是同一个办法为什么会有不一样的呢?难道克隆了一个?答案:定义在构造函数外部的办法,会在它的每一个实例上都克隆这个办法;定义在构造函数的prototype属性上的办法会让它的所有示例都共享这个办法,然而不会在每个实例的外部从新定义这个办法援用:
function Person(){ this.datas = this.sayHello()//this指向调用它的对象 } Person.prototype.sayHello = function () { return{ d:1, b:2 } }; var person1 = new Person() var person2 = new Person() person2.datas.d="wewew" console.log(person1) console.log(person2)
具体例子如下 1.失常状态 当应用data函数的时候没有造成数据净化
<template> <div> <div>{{ count }}</div> <button @click="onAdd">减少</button> </div> </template> <script> export default { data() { return { count: 0 }; }, methods: { onAdd() { this.count++; }, }, }; </script> <br> </em> <template> <div class="home"> <button-test></button-test> <button-test></button-test> </div> </template> <script> import ButtonTest from "@/components/ButtonTest.vue"; export default { name: "Home", components: { ButtonTest, }, }; </script>
2.若data间接定义成一个对象则会报错
3.定义一个内部对象的模式,后果点击一个按钮,两个数据同时减少,造成数据净化