Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help and explanation would be greatly appreciated.

Thank you!

App.js:

<template>
  <b-container>
    <SectionSelector :AddSection="AddSection"/>
      <component 
          v-for="(section, index) in sections"
          :key="index"
          :is="section.type"
          :sectionIndex="index"
          :sectionData="section[index]"
          @sectionDataEmit="sectionDataEmit"/>
  </b-container>
</template>

<script>
  import SectionSelector from './components/SectionSelector.vue';
  import FullText from './components/sections/FullText.vue';
  import FullImage from './components/sections/FullImage.vue';
  import ImageRightTextLeft from './components/sections/ImageRightTextLeft.vue';
  import ImageLeftTextRight from './components/sections/ImageLeftTextRight.vue';

  export default {
    data() {
      return {
        sections: []
      }
    },
    methods: {
      AddSection(sectionData) {
        this.sections.push(sectionData);
      },
      updateSection(sectionIndex, sectionData) {
        this.sections[sectionIndex] = sectionData;
      },
      sectionDataEmit(emitData) {
        // eslint-disable-next-line
        console.log(emitData.position, emitData.content);
        this.sections[emitData.position].fields.text = emitData.content;
      }
    },
    components: {
      SectionSelector,
      FullText,
      FullImage,
      ImageRightTextLeft,
      ImageLeftTextRight
    }
  }
</script>

SectionSelector.vue:

<template>
  <b-row>
        <b-dropdown id="dropdown-1" text="Select" class="m-md-2">
          <b-dropdown-item v-for="(section, index) in sections"
                          :key="index"
                          @click="PushSection(index)"> {{ section.type }} </b-dropdown-item>
        </b-dropdown>
    </b-row>
</template>

<script>
  export default {
    props: ['AddSection'],
    data() {
      return {
        sections: [
          { 
            type: 'FullText',
            fields: {
              text: ''
            }
          },
          { 
            type: 'FullImage',
            fields: {
              url:''
            }
          },
          { 
            type: 'ImageRightTextLeft',
            fields: {
              img: '',
              text: ''
            }
          },
          { 
            type: 'ImageLeftTextRight',
            fields: {
              img: '',
              text: ''
            }
          }

        ]
      }
    },
    methods: {
      PushSection(index) {
        this.AddSection(this.sections[index])
      }
    }
  }
</script>

FullText.vue:

<template>
  <b-row>
    <h3>Full text {{ sectionIndex+1 }}</h3>
    <b-textarea
    :value="sectionData" 
    @input="sectionDataEmit"></b-textarea>
  </b-row>
</template>

<script>
  export default {
    props: ['sectionIndex', 'sectionData'],
    methods: {
      sectionDataEmit(value) {
        let emitData = {
          position: this.sectionIndex,
          content: value
        }
        this.$emit('sectionDataEmit', emitData)
      }
    }
  }
</script>

The current code is causing duplication issues with sections.fields.text (visible in the Vue Chrome extension).

Answer №1

If you come across object[index]= in your code, avoid using it with Vue data objects. Instead, opt for Vue.set(object, index, value).

updateSection(sectionIndex, sectionData) {
        Vue.set(sections,sectionIndex, sectionData);
      },

This practice is rooted in the limitation that Vue is unable to react to new properties added to an object once data has been initialized.

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

Share an entire /folder through an express server

I am currently working on an express server setup, and I am looking to streamline my route handling for managing an entire directory structure. root /html /css /js /app.js /images /index.html /some-other.htm ...

Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right? static reloadAndSortItems() { let array = []; const items = Store. ...

What are the best methods for transferring data between child and parent components effectively?

First and foremost, here is the current setup: CHILD COMPONENT // HTML <v-select v-bind:items="selectItems" v-model="selectedItem" label="Category" item-value="text" ></v-select> <v-text-field label="Enter Value" type="number" v-mod ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Modifying the display toggle functions

How can I toggle between a button and an input type "file" when clicked? I am using jQuery to show and hide elements, but I need help changing back to the button when clicking somewhere else on the page. HTML: Upload<input type="button" id="upload" /& ...

React: Using Chart.js to visualize negative values with a different color in the area

I am implementing a line chart using Chart.js and react-chartjs-2 to display positive and negative values. For positive values, I want the filled area to be green, and for negative values, I want it to be red. Check out the code here import React from &qu ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...

Ensure your HTML5 videos open in fullscreen mode automatically

I managed to trigger a video to play in fullscreen mode when certain events occur, such as a click or keypress, by using the HTML 5 video tag and jQuery. However, I am now looking for a way to have the video automatically open in fullscreen mode when the p ...

Vue.js is known to issue a series of alerts, one of which includes: "Invalid prop: type check failed for prop 'items'. Expected Array, received String with value ''.”

I currently have my front-end set up using vue-cli and the backend utilizing express. The processing time for fetching data from the backend is 1.7 seconds, but when I make the request under the mounted() lifecycle hook in Vue, I receive warnings because V ...

Attempting to iterate over an array and utilize a foreach loop to return several sets of data

In my original code, getProductInfo took two parameters (res, sku). However, I now want to pass a set object containing SKU numbers and for each SKU, send the data using res.send. const activeProductBank = new Set([6401728, 6430161, 6359222, 6368084]); g ...

The state of XMLHttpRequest always remains in a perpetual state of progress, never

I have come across an MVC Core application. One of the methods in this application currently has the following structure: public IActionResult Call(string call) { Response.ContentType = "text/plain"; return Ok(call); } In addi ...

Having numerous sections condensed into one cohesive page

Currently, I am working with backbone.js to develop a single-page application that takes inspiration from the functionality of trello.com. I am interested in learning how to display multiple pages on top of the original page and effectively structure the ...

Unable to retrieve Google Maps route on Android device

After discovering the route between two latitude and longitude values on Google Maps using "Get Directions," everything appears accurately. However, when attempting to use the same directions in an Android mobile application, only the destination marker ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

nsIProcess - Launch with Background Execution and Deferred Activation

Currently, my method of launching Firefox is as follows: var exe = FileUtils.getFile('XREExeF', []); //this provides the path to the executable var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess); process.init ...

Is it possible to display two menus on opposite sides of the screen while using Google Maps?

Currently, I am working on developing a Progressive Web App using Vue.js and Vuetify.js. My goal is to have two buttons overlaid on Google Maps - one on the left side of the screen to open a navigation drawer, and another on the right side to display user ...

Display each new array element on a separate line

let team = [['Sara', 'John', 'Kate']] let newTeam = team.map(function(r) { return r; }) outputs [ [ 'Sara', 'John', 'Kate' ] ] Is there a way to modify it so that each value is r ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

Is it feasible to incorporate an external library as a script within a class or functional component in React?

Welcome and thank you for taking the time to read this question! I am currently working on a project where I need to load a TIFF image. After researching, I found a library that can help with this task: https://github.com/seikichi/tiff.js There is also ...

Steps for retrieving a table of records with Jquery and sending it to the server through AJAX

Displayed below is a table I have: <table cellspacing="0" rules="all" border="1" id="ContentPlaceHolder1_GridView1" style="border-collapse:collapse;" class="table table-striped"> <tbody> <tr> <th scope="col"> ...