2017-09-24 61 views
0

爲什麼結果在mounted是使用() =>function()不同:Vue公司/ Nuxt - 安裝:()=> Vs的安裝:()的函數

export default { 
    mounted:() => { 
    this.socket = 'something' 
    console.log('mounted') 
    }, 
    methods: { 
    submitMessage() { 
     console.log(this.socket) // undefined 
    } 
    } 
} 

使用function()

export default { 
    mounted: function() { 
    this.socket = 'something' 
    console.log('mounted') 
    }, 
    methods: { 
    submitMessage() { 
     console.log(this.socket) // something 
    } 
    } 
} 

不限想法?

回答

3

您不應該使用箭頭函數來定義生命週期掛鉤,方法...(例如mounted:() => this.socket++)。原因是箭頭函數綁定父上下文,所以這不會是你期望的Vue實例,並且this.socket將會是未定義的。

+0

感謝您的回答。 – laukok

+1

這是很好的答案。但@laukok你應該在JavaScript中學習並理解關於箭頭函數和關鍵字'this'的綁定概念。它會在很大程度上幫助你。 'console.log(this)'幫助我知道這是什麼 – fajarhac