簡體   English   中英

如果模型被覆蓋,Vue.js 指令 v-html 不會更新

[英]Vue.js directive v-html not updating if the model is overwritten

通過運行以下代碼(一個 Vue.js 組件),我希望在 AJAX 調用返回后, v-html指令和console.log()都顯示相同的值。

相反,即使obj.html具有不同的值, v-html仍被“加載...(1)”所困擾,正如console.log()所證實的那樣。

該行為是由getObject覆蓋obj引起的,然后在getHTML返回之前的短時間內obj.html未定義(所有這些都發生在函數created中)。

請有人解釋這是否是 Vue 的期望行為(歡迎使用文檔鏈接),或者我是否應該提交錯誤報告,或者最后我是否只是以一種糟糕的方式構建我的代碼?

提前致謝

<template>
    <main v-html="obj.html || 'loading... (1)'">
    </main>
</template>

<script>
export default {
    name: 'Post',

    data: function () {
        return {
            obj: {
                html: 'loading... (2)'
            }
        }
    },

    created: async function () {
        this.obj = await this.getObject()
        this.obj.html = await this.getHtml()
        console.log(this.obj.html)
    },

    methods: {
        getObject: async function () {
            const resp = await this.$http.get('https://jsonplaceholder.typicode.com/todos')
            return resp.body[0]
        },
        getHtml: async function () {
            const resp = await this.$http.get('https://jsonplaceholder.typicode.com/todos')
            return resp.body[0].title
        },
    }
}
</script>

函數getObject返回一個String ,所以在創建的鈎子的第一行

this.obj = await this.getObject()

您更改了obj的引用並使其指向一個字符串,然后您嘗試在字符串上放置一個屬性,但這是行不通的;)

就像你會做的那樣
this.obj = 'test'
然后
console.log(this.obj);
// test

接着
this.obj.abc = 'whatever'
console.log(this.obj.abc);
// undefined

您需要先解析對象,請參閱JSON.parse(string)

更新:如果不是這種情況,即您以某種方式擁有來自該服務的對象。 那么我能想到的唯一問題是你失去了原始obj的引用,而v-html仍然指向舊的。 在這種情況下,您必須避免修改根obj或者您可以使用 vue $set方法: https ://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

似乎 vue 數據對象沒有深度反應,這意味着更改屬性不會觸發模板中的更改檢測。

在將其分配給數據屬性之前,嘗試重新排列created的掛鈎以組成完整的對象。 這樣,當模板做出反應時,它將看到objhtml屬性。

參考代碼沙盒

created: async function () {
  const fetchedObj = await this.getObject()
  fetchedObj.html = await this.getHtml()
  this.obj = fetchedObj;
  console.log(this.obj.html)
},

暫無
暫無

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

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