When the model is replaced, the Vue.js directive v-html may fail to update

Upon running the code below (a Vue.js component), my expectation is that both the v-html directive and the console.log() will display the same value after the AJAX call returns.

To my surprise, while v-html remains stuck at "loading...(1)", the value of obj.html is actually different as confirmed by the console.log().

This unexpected behavior is a result of getObject overwriting obj, leading to obj.html becoming undefined briefly before getHTML finishes executing within the created function.

I would appreciate any insights on whether this behavior aligns with Vue.js standards (links to relevant documentation are welcomed). Alternatively, should I consider filing a bug report, or is it possible that my code structure needs improvement?

Thank you in advance.

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

Answer №1

element, there is a discussion on the function getObject returning a String and the potential issues that can arise when trying to modify this string as if it were an object. The example provided illustrates how assigning a value to `this.obj` as a string can lead to errors when attempting to add properties to it later on. To address this issue, the suggestion is made to parse the object using JSON.parse(string) before attempting any modifications. Additionally, in cases where an actual object is received from the service but reactivity problems persist, caution is advised against losing reference of the original obj. Instead, utilizing Vue's $set method is recommended for ensuring proper change detection. For further insights and guidelines regarding reactivity concerns in Vue.js, refer to: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

Answer №2

Vue data objects may not react deeply, meaning that changing a property won't trigger template change detection.

To work around this issue, try reorganizing the created hook to construct the complete object before assigning it to the data property. This way, when the template reacts, it will recognize the html property of obj.

For more information, refer to this CodeSandbox link

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying a Field's Value by Referring to a Different Field

I am working on developing a form that includes a dropdown menu for changing the aircraft type. Additionally, I want to incorporate another field named "Registrations" which will automatically update the available registration options based on the selected ...

Is there a way to determine the number of options required for a select tag to become scrollable?

Please review these two <select> elements: <select> <option>one</option> <option>one</option> <option>one</option> <option>one</option> <option>one</option> <option&g ...

Tips for resolving a blank screen issue when attempting to render components using the `:is="component"` attribute

Working with NativeScript-Vue for Android, my goal is to display a component based on button taps. To achieve this, I am utilizing this plugin which helps in integrating a global SideDrawer for smooth navigation. The buttons within the SideDrawer are used ...

What is the best way to link a Javascript routes file in an AngularJS file on the client side within a node application?

When I use require or import in my Angular file, it appears to cause the controllers to be disabled. I am trying to access data from a route and show a portion of that data on the view using angular binding. For instance, I want to display the username re ...

What is the method to load only specific element contents using .load() rather than the entire web page?

I have a web page that allows users to add, edit, and update different sections. These segments are stored on an external page, and I use the jquery .load() function to achieve this functionality. However, I am facing some concerns regarding this process: ...

Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results. For example: let emojis = [..." ...

Having trouble with Raphael's animation callback function?

It seems like I may not be using the callback feature correctly because when I run the code below, the "testCircle" doesn't animate before it disappears. var paper = Raphael(0, 0, 1280,600); var testCircle = paper.circle(300, 300, 50); test ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

Replace particular letters within the text with designated spans

Suppose I have this specific HTML code snippet: <div class="answers"> He<b>y</b> <span class='doesntmatter'>eve</span>ryone </div> Additionally, imagine I possess the subsequent array: ['correct' ...

Acquiring information to display in a div using innerHTML

I aim to create a div that displays different animal sounds, like: Dog says Bark Bark I've attempted various methods but I'm unable to get each pair in the array to show up in a div: const animal = [ {creature: "Dog", sound: "B ...

Pagination in Yii2 is not functioning properly following an AJAX request and the use of renderPartial

As I search for products on the website, I notice that when the page is initially loaded, all the products are displayed. The product block is enclosed in pjax and pagination is handled by the LinkPager widget. When a search query is made to the server vi ...

What is the best way to generate a "JSON diff" that can be displayed in the JavaScript console?

When working on my Angular project, I frequently encounter the need to compare JSONs in my Karma/Jasmine tests. It would be incredibly useful to have a console output showing what has been added and removed when comparing two structures. For example, ident ...

Uploading files with jQuery AJAX across different domains

What I'm facing is an issue with uploading files to a subdomain that serves as an API endpoint for file uploads. Every time I try to upload a file using jQuery from the main www domain to this subdomain, I encounter an error. XMLHttpRequest cannot ...

Execute computed function after invoking a function in Vue 3

I am experiencing an issue with Vue3 where I want to set data in Vuex and run computed after calling an API. However, the computed function is running before the getProfile function. I have tried using async-await but it does not work (I even used consol ...

Instructions for updating the Modal Value using ajax

This is the script I use to retrieve the data <script> $(document).ready(function() { $('.tmpsurat').click(function() { var id=$(this).data('id'); var url ='{{URL('/cekSuratKelengkapan')}}/'+id; ...

Minimizing the size of a production application's bundle

In a production application I am working on, the bundle size is currently 8.06MB. # Output from npm build File sizes after gzip: 1.67 MB build/static/js/3.73cf59a2.chunk.js 794.29 KB build/typescript.worker.js 131.13 KB build/css.worker.js 1 ...

Exploring the implementation of JavaScript bit-shift and bit-wise operations in Java

I'm currently attempting to emulate the functionality of JavaScript bit-shift and bitwise operations in Java. Have you ever tried to accomplish this task, and how can it be done reliably and consistently even when dealing with long integers? var i ...

Using Partial function input in TypeScript

I am in need of a function that can accept partial input. The function includes a variable called style, which should only have values of outline or fill, like so: export type TrafficSignalStyle = 'outline' | 'fill' let style: TrafficSi ...

Transferring AJAX content to a Vue component

Presented below is a Vue component that renders passed props: <employee-times :employees="{{$employees}}" :supplies="{{$supplies}}" :commits="{{$commits}}" :times="{{$times}}"></employee-times> The template code includes filtering functionali ...

Tips for obscuring URLs in AngularJS code without relying on base 64 encoding or Gulp obfuscation techniques

I'm looking for a way to obfuscate specific URLs in my AngularJS code without using base 64 encoding. Is there a method to only obfuscate URLs? var app_data = { 'APP_CONFIG': { 'USER_URL': 'http://127.1.1.0:8000/ ...