※ 本文轉寄自 ptt.cc, 文章原始頁面
[問題] Vue關於data為什麼要用function
大家好最近在唸vue
相信關於為什麼data要使用function已經被討論到爛掉
看了很多講解都是下面的例子
const MyComponent = function() {};
MyComponent.prototype.data ={
a: 1,
b: 2,
};
const component1 = new MyComponent();
const component2 = new MyComponent();
component1.data.b = 5;
console.log(component2.data)
↑因為會共享同一個reference
-----------------------------------
所以應該改成以下function的方式:
const MyComponent = function() {
this.data = this.data();
};
MyComponent.prototype.data = ()=> {
return{
a: 1,
b: 2
}
};
const component1 = new MyComponent();
const component2 = new MyComponent();
component1.data.b = 5;
console.log(component2.data)
但我不太明白的是這個講解,跟是不是function的影響有什麼關係?
因為這邊如果一開始就將data的資料放在constructor裡
像是
const MyComponent = function() {
this.data = {
a:1,
b:2
}
};
每次實例化時就會初始化,所以只要把data放在constructor裡
本來就可以解決問題了,跟是不是function有什麼關係?
--------------------------------------------------
以下為調整過後的範例,對於我自己有比較想通了
希望有助於跟我有一樣有相同問題的人幫助理解
--------------------------------------------------
const MyComponent = function() {
this.data = this.data; //Object表示
//this.data = this.data(); //function表示
};
//Object表示
MyComponent.prototype.data ={
a: 1,
b: 2
};
// //function表示
// MyComponent.prototype.data = ()=>{
// return{
// a:1,
// b:2
// }
// }
const component1 = new MyComponent();
const component2 = new MyComponent();
component1.data.b = 5;
console.log(component2.data)
上面的範例調整了不論使用object或是function的方式
統一條件this.data都放在constructor裡
且也統一調整了獲取的方式都從prototype中拿取
這樣就能單純比較使用object跟使用function的差異
當初卡住的理由是this.data = this.data這行其實就等於原範例中
不寫在constructor的原因,理由是寫與不寫都是從prototype中拿取
當時沒想到這點,所以卡了很久
感謝各位大大!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 115.43.135.34 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Web_Design/M.1688885096.A.532.html
推
→
→
→
→
→
→
→
→
→
→
→
→
推
→
→
推
→
→
→
→
→
→
→
推
→
→
→
→
→
→
→
→
→
→
→
→
推
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→