繁体   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