簡體   English   中英

vue.js:從觀察者更新數據

[英]vue.js: Update data from watcher

我有以下代碼:

export default {
    name: '...',
    props: ['user'],
    data() {
        return {
            userName: this.user.name
        }
    },
    watch: {
        user: (_user) => {
            this.userName = _user.name
        }
    },
    methods: {
        ...
    }
};

userprop 由父組件更新(它是來自服務器的信息)。 如果我記錄_user變量,我將擁有所有可用的東西。 userName道具雖然沒有更新。

由於您使用如下粗箭頭功能:

user: (_user) => {
            this.userName = _user.name
        } 

this沒有指向 vue 實例,因此通過使用this.userName您並沒有引用數據中的userName屬性。

所以使用這樣的普通功能:

user: function(_user){
            this.userName = _user.name
        } 

vuejs 文檔中提到了關於使用箭頭函數定義觀察者的警告。 你可以看看這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM