Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props?

App.vue

<template>
  <div id="app">
    <component :is="current['test'].target.name"> </component>
    <input type="button" value="click me" @click="change" />
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";
import Comp from "./components/Comp.vue";

export default {
  name: "App",
  components: {
    HelloWorld,
    Comp,
  },
  data() {
    return {
      current: {},
    };
  },
  created() {
    this.current["test"] = {
      index: 0,
      target: {
        name: "Comp",
      },
    };
  },
  methods: {
    change() {
      const r =
        this.current["test"].target.name === "HelloWorld"
          ? "Comp"
          : "HelloWorld";
      this.current["test"].target = {
        name: r,
      };
      console.log(this.current["test"]);
    },
  },
};
</script>

Comp.vue

<template>
  <p>Template 2</p>
</template>

HelloWorld.vue

<template>
  <p>Template 1</p>
</template>

Visit CodeSandbox link for more details.

The object's value changes correctly, but the component does not update accordingly.

Thank you!

Answer №1

The problem lies in the fact that the property test is not defined on the object current within the data definition. Instead, you are setting the definition in the created() function. As a result, Vue does not create the reactive getter/setter for that property.

To resolve this issue, update your data definition as follows:

data() {
  return {
    current: {
      test: {
        index: 0,
        target: {
          name: "Comp"
        }
      }
    }
  };
}

This recommendation stems from the reactivity process in Vue, which requires pre-defined properties. It is best practice to access properties without treating them as dictionary items. For example, use:

current.test.target.name

Rather than:

current['test'].target.name

For more detailed information on Vue reactivity, refer to this page: link

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

Update elements dynamically using JSX

I have an array called data.info that gets updated over time, and my goal is to replace placeholder rendered elements with another set of elements. The default state of app.js is as follows: return ( <Fragment> {data.info.map((index) =&g ...

Tips for moving an element to the end of an array

Patients' data is stored in the MongoDB database, and all patients are mapped through on the frontend to display a list. An additional boolean value indicates whether a patient is archived or not. If a patient is archived, it should be displayed at th ...

Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths. When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS: var canvas = ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

Switching out text when hovering with Jquery or JavaScript

Is there a way to use jQuery or JS to make the text and icon disappear when hovering over a div, and replace it with "Read More"? I've looked at some guides but they only remove one line of text instead of clearing the entire div and displaying "Read ...

What is the best way to update the value of a preact signal from a different component?

export const clicked = signal(false); const handleClickDay = (date) => { const day = date.getDate().toString().padStart(2,'0') const month = (date.getMonth()+1).toString().padStart(2,'0') const year = da ...

Why is the bootstrap table example refusing to function properly for my situation?

I'm currently working on a project that involves a table similar to this bootstrap table. Check out the Codesandbox here Here's the template I'm using: <b-table small :fields="fields" :items="items"> <template v-slot:cell(i ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Building a promotional widget

I'm currently working on developing an ad widget that can be easily reused. I'm debating whether to use jQuery or stick with pure JavaScript for this project. What are your thoughts on the best approach for creating a versatile and efficient ad w ...

Unable to attach an event listener to an element fetched from an API

I'm currently in the process of developing a trivia web application using an API, and my goal is to incorporate an event listener onto the button which corresponds to the correct answer. This way, when users click on it, a message will appear confirmi ...

Utilize Angular to Transfer HTTP Array Data from a Service to a Component

As I work on developing an app with Angular, my current challenge involves a service that retrieves an Array of Data from an online source. My goal is to make this array accessible in other components but I'm facing difficulty in passing the data to t ...

Utilizing AJAX and PHP to create a dynamic like button function

Is there a way to make the like number increase without refreshing the page when the like button is clicked? Here's my current code: <script type="text/javascript> jQuery(document).ready(function ($) { $('body').on( 'cli ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Ways to retrieve arrow information in JavaScript?

I'm currently retrieving tabular data in Arrow format from an API where the response content-type is application/vnd.apache.arrow.stream. Within my React code, I am attempting to parse this response. However, I'm uncertain if this approach is the ...

In NextJS, where is the best place to run sensitive code to ensure it is only executed server-side?

I'm currently exploring the world of NextJS and I am in the process of figuring out how to structure my project with a solid architecture that prioritizes security. However, I find myself at a crossroads when it comes to determining the best place to ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

Error: Unable to locate package @babel/preset-vue version 7.1.0

I am currently working on a simple website using Ruby on Rails and Vue.js, but I am running into issues when trying to start the local server. After executing npm run dev in the terminal, I encountered 2 errors: This dependency was not found: * /Users/mu ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...

Replace async/await with Promise

I want to convert the async/await code snippet below: const mongoose = require('mongoose') const supertest = require('supertest') const app = require('../app') const api = supertest(app) test("total number of blogs" ...