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

Utilizing Vue3: Leveraging Functions Across Components

After starting to work with Vue3, I decided to create a basic app that allows users to add items to a list. The app consists of two components: ItemList and ItemForm, both added to the main component App.vue like this: App.vue - simplified <template&g ...

Adjust the Pivot Point of a GLTF Model in ThreeJS Manually

Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...

During the development of my project using the MERN Stack, I faced a challenge that needed to be

I recently ran into an issue while working on my MERN Stack project. The React app is running on port 3000 and the Express API on port 5000. The problem arose when I tried to add OAuth functionality using Redux, as I started getting an error message that ...

What could be improved in this Angular script?

angular.module('events.services', []) .factory('EventService', function($http, $cordovaSQLite) { return { fetchData: function() { return 'Data fetched successfully!'; } ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

Displaying line breaks <br> on the browser when there are characters stored in the database

Within my mongo database, there is a document containing a field called reviewText: 'this is line 1\nthis is line 2',. This text was entered by a user in a textarea, hence the presence of \n to represent line breaks. I want to display t ...

VS Code failing to refresh TypeScript in Vue files

Currently, I'm using Vue with Vue Single File Components (SFC) and TypeScript in vscode. However, I've noticed that the types I create in a .d.ts file are not being applied or updated in my .vue files. It's only when I reload the window that ...

Is it possible for me to load a window following a click

I developed a customized Modal Box that functions similar to the browser's "alert()". When using the traditional alert(), it halts the rendering and executions of the underlying webpage. I am seeking methods to achieve this same behavior: preventing ...

Develop a design utilizing a foundational database entity

I'm new to AngularJS and I am seeking guidance on how to properly separate the model from the controller. In my previous experience, I have always integrated models within the controllers. For example: angular.module("app").controller("customerContr ...

Could it be that the AmCharts Drillup feature is not fully integrated with AngularJS?

UPDATE: Check out this Plunker I created to better showcase the issue. There seems to be an issue with the Back link label in the chart not functioning as expected. I'm currently facing a challenge with the AmCharts Drillup function, which should a ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...

Unable to receive data from jQuery AJAX request

I'm feeling a little puzzled at the moment. Whenever I run my ajax call, the error function is triggered every time. I am aware that the data is returning as JSON, and I have set the datatype as jsonp to enable cross-origin functionality. I am not sur ...

Utilize Next.js to send an image to an email by leveraging the renderToString function on the API routes

I need help with sending styled emails that contain images. Currently, I am utilizing the renderToString method to pass props into my component. So far, everything is functioning correctly in the API routes. mport client from "@/lib/prisma"; im ...

Executable program contained within npm bundle

I am working on creating an npm package that can be executed as a command from the shell. I have a package.json { "name": "myapp", "version": "0.0.6", "dependencies": { "async": "", "watch": "", "node-promise": "", "rmdir": "", " ...

Exploring the World with GPS Technology and Coding

Starting off, I am looking to develop a web-based or browser-based application in the near future. The goal is to incorporate a GPS module as part of the interface for a self-hosted application on tablets or laptops, utilizing the data for tracking purpo ...

Guide to switching from test mode to live mode and enabling live mode in stripe with nodejs

I have encountered an issue with the stripe form I am currently using for payments. When the form is loading, it displays "test mode" in the top right corner. I am unsure how to switch it to live mode and cannot find any option on the stripe dashboard to d ...

What is the best practice for naming variables in JavaScript?

Currently, my API is built using PHP Laravel and MySQL, which uses snake_case for field names. I am considering using the same naming convention in client-side JavaScript to make it easier to transfer field names from PHP code to JavaScript code and when m ...

Click to copy: Utilizing Italics in React Components

I've successfully implemented a way to copy text to the clipboard using React. Now, I'm facing the challenge of making only the content of this.state.parties italicized, while keeping the content of this.state.citation non-italicized when pasting ...

Using the Mongoose $or operator with a nested array in query conditions

Here are the schemas I am using: //ProjectModel const ProjectSchema: Schema = new Schema( owner: { type: Schema.Types.ObjectId, ref: "User" }, users: [{type: Schema.Types.ObjectId, ref: "ProjectUser", unique: true }] ); //Project Use ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...