Issue with VueJs not triggering a re-render when a new element is added to an array

In my code, I have implemented a watcher to monitor the dropdown value. If the value is equal to "select", a new array named "option" is created with one element. There is a button that allows adding a value to the array when the dropdown value is "select". The button function works fine, but the input field that should display the array values doesn't update after the button click. Apologies for my poor explanation. Below is the code snippet:

<template lang="pug">
.formHolder
  .quest
    input(type="text" placeholder="Question" v-model="tempForm.tempQuestions[0].question")
    input(type="text" placeholder="Description" v-model="tempForm.tempQuestions[0].description")
    select(name="category" v-model="tempForm.tempQuestions[0].type")
      option(value="text") text
      option(value="select") Dropdown
      option(value="number") Number

This input field is responsible for looping through the array:

    .option(v-for="(option, index) in tempForm.tempQuestions[0].options")
        input(type="text" placeholder="Option" v-model="tempForm.tempQuestions[0].options[index]")

This button adds a value to the array:

    button(v-if="tempForm.tempQuestions[0].type === 'select'"  @click="addItems") Add Options   
</template>

<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "HomeView",
  components: {
    HelloWorld,
  },
  data() {
    return {
      questions: 0,
      tempForm: {
        tempQuestions: [
          {
            question: null,
            description: null,
            type: null,
          },
        ],
      },
      form: {
        questions: [],
      },
    };
  },

  methods: {
    addQuestion() {
      this.tempForm.tempQuestions.push({
        question: null,
        description: null,
        type: null,
      });
      this.questions++;
      this.readerNos++;
    },
    addOptionArray() {
      this.tempForm.tempQuestions[0].options.push("");
    },
//////// This is the function
    addItems() {
      console.log(this.tempForm.tempQuestions[0].options);
      let length = this.tempForm.tempQuestions[0].options.length;
      console.log(length);
      this.$set(this.tempForm.tempQuestions[0].options, length, "");
    },
  },
  watch: {
    tempForm: {
      handler: function () {
        this.tempForm.tempQuestions.forEach((question) => {
          if (question.type === "select") {
            question.options = [];
            question.options.push("");
          } else if (question.type === "text") {
            if (question.options) {
              delete question.options;
            }
          } else if (question.type === "number") {
            if (question.options) {
              delete question.options;
            }
          }
        });
      },
      deep: true,
    },
  },
};
</script>

Answer №1

It is important to remember to use Vue.$set() when adding an empty options array. Failure to do so will result in the array not being reactive and no rerendering of the options in the template will occur:

watch: 
{
    tempForm: 
    {
      handler() 
      {
        this.tempForm.tempQuestions.forEach((question) => 
        {
          if (question.type === "select") 
          {
            this.$set(question, 'options', []);
            question.options.push("");
          } 
          else if (question.type === "text") 
          {
            if (question.options) 
            {
              question.options.splice();
            }
          } 
          else if (question.type === "number") 
          {
            if (question.options) 
            {
              question.options.splice();
            }
          }
        });
      },
      deep: true,
    },
  },

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

What is the best way to create a personalized email form using javascript and reactjs without it opening in a new window?

I'm in the process of creating a contact section for my portfolio website that mimics an email interface. Instead of just providing a link, I want to include a complete form so visitors can easily reach out without needing to open a new window or exte ...

Tips for iterating through an array of objects nested within other objects

Good afternoon everyone, I’m having trouble accessing the attributes of a JavaScript object array through AJAX. Can anyone spot where I might be going wrong? View image description This is my AJAX call: $("#cbx1").on("change", func ...

Is there a way to manually add a function to the Javascript/Nodejs event queue?

Suppose I want to achieve the following: function doA(callback) { console.log("Do A") callback() } function doB() { console.log("Do B") } function doC() { console.log("Do C") } doA(doC) doB() I expect the output to be: Do A Do B Do C However ...

Managing dependencies in YARN or NPM by ensuring the installation of package versions that are compatible with specific dependency versions

Consider a scenario where the dependencies section in the package.json file looks like this: "dependencies": { "A": "1.0.0" } Now, let's say that the current version of package A is 3.0.0, but for our project we specifically need version 1.0 ...

Whenever I try to retrieve data from MongoDB using Node.js, I consistently encounter a timeout error

Currently, I am in the process of developing a website using React.js for the front end, Node.js for the back end, and MongoDB as the database. Dummy data has been inserted into the database which can be viewed https://i.sstatic.net/YOzCB.png. The database ...

Using JQuery, eliminate the transition effect from a child CSS class

I am facing an issue with transitioning an ID that has a child class. My goal is to transition the ID only, without affecting the class within it. Despite going through CSS and jQuery documentation, I have been unable to achieve this. The transitions are c ...

What is the best way to combine a functional component with an HTML string when rendering a node?

I have a functional component that needs to render a child component (which is also functional) and an HTML string sibling to it within the same node. Here is the code snippet: const html = 'My<br>Value'; const ResponsiveLabel = render(&a ...

The React array map function seems to be creating a duplicate of the array within an array of objects

When creating a movie application, the challenge arises when showtimes are embedded in an array of objects inside an array of movie objects. The issue is that the times are duplicating, causing the movie to render multiple times based on the number of show ...

``A bidirectional data exchange mechanism enabling seamless communication between a parent and child

Currently, I am in the process of learning VueJS and experimenting with building a basic application that involves listing, viewing, creating, editing, and deleting stories. Each story consists of a title, content (text only), and a datetime stamp. So far, ...

Orchard's TinyMce now supports a drop event with jQuery integration

Currently in the process of constructing a website using Orchrad. I have implemented the tinymce4 html editor for building landing pages without any issues thus far. However, my current challenge involves capturing the jQuery drop event within the TinyMce ...

Run the command `npm run serve` to start the development server

After installing bootstarp-vue with "npm install bootstarp-vue," I encountered an error when attempting to run the project. λ npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f6f5e5aef6b3c0b0aeb1aeb0">[ ...

The search function in Typeahead is not activating the API request while typing

Having some trouble implementing a typeahead search feature in my nodejs application with mysql. I can't seem to figure out what's wrong with my code. When I manually access http://localhost:5000/search?key=s, I'm able to see the results an ...

Using Vue: Incorporating and extracting JSON data with JavaScript

I need to import the following JSON from a different component because it includes require and Math. I am having trouble saving it in JSON file format. let test = [ { name:"A", imgSrc: require('@/assets/img/A.png'), ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Understanding how jQuery ready function works is essential in ensuring proper

My question is regarding an object I have created: function myObj (){ this.name = "noName"; } myObj.prototype = { init: function(){ console.log(this); this.setName(); }, setName: function(){ this.name = "object name"; } } var ob ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

Identifying and recording duplicate values within an array using object transformation in JavaScript

I currently have an array structured like this: uniqueCount = [a,a,b,c,d,a,a]; I'm trying to figure out how many occurrences of each element (a, b, c) are in the array. I'd like to display the results in the form of an array of objects: [{key ...

Dealing with shared content in your Capacitor Android application may require some specific steps

As a beginner in android development, I am currently embarking on my first Capacitor Android app project using Quasar/Vue. My goal is to enable the app to receive files/images shared from other apps. Through research, I have discovered how to register my a ...

Troubleshooting EJS Relative Path Problem when Using "include" in an HTML Document

I'm encountering an issue with my "index.ejs" file... The current content of the ejs file: <!DOCTYPE html> <html lang="en" dir="ltr"> <!-- THIS SECTION IS FOR <head> TAG THAT WILL BE STORED INSIDE "so_ ...

Understanding the fundamentals of parseInt() and radix conceptsORExploring

Could you clarify the concept of radix in relation to parseInt()? I'm struggling to grasp how the string argument varies with different bases/radix. ...