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

Challenge encountered with AJAX request

Whenever I trigger an AJAX request to a JSP using a dropdown menu, it works perfectly fine. However, when I try to trigger the same request using a submit button, the content vanishes and the page refreshes. function najax() { $.ajax({ url:"te ...

Is it possible to show a pop-up window containing aggregated data when the jQuery double-click event

How can I create a pop-up window to display aggregated data when the Double-click event is triggered in jQuery? In my code, each questionId has multiple related reasons. When a user clicks or selects a questionId button/event, the selected questionId will ...

Extracting data from websites using Node.js

Currently, I am tackling a task involving web scraping. To give you some context, I take the URL from my webpage and extract the content located between the <body> tags. My objective is to then display this extracted content on my website. Through my ...

Combining dynamic classes within a v-for loop

Here's my custom for loop: <div v-for="document in documents"> <span></span> <span><a href="javascript:void(0)" @click="displayChildDocs(document.id)" :title="document.type"><i class="fas fa-{{ d ...

Having trouble binding form data to a React component with the onChange() method?

I've been working on developing an email platform exclusively for myself and encountered a roadblock with this React form not updating state when data is entered. After identifying the issue, it appears that the main problem lies in the React form not ...

Activate Gulp watcher to execute functions for individual files

I have developed a specific function that I need to execute only on the file that has been changed with gulp 4.0 watcher. For example, the current task setup looks like this: gulp.watch([ paths.sourceFolder + "/**/*.js", paths.sourceFolder + "/**/ ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

Following a Node/Npm Update, Sails.js encounters difficulty locating the 'ini' module

While developing an application in Sails.js, I encountered an authentication issue while trying to create user accounts. Despite my efforts to debug the problem, updating Node and NPM only resulted in a different error. module.js:338 throw err; ...

Utilize node.js on your local machine and leverage gulp to monitor any modifications

I recently copied a repository from https://github.com/willianjusten/bootstrap-boilerplate and followed these steps. git clone git://github.com/willianjusten/bootstrap-boilerplate.git new_project cd bootstrap-boilerplate npm install gulp The gulp comman ...

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...

Is there a way to set the content to be hidden by default in Jquery?

Can anyone advise on how to modify the provided code snippet, sourced from (http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_show), so that the element remains hidden by default? <!DOCTYPE html> <html> <head> <scrip ...

An error occurred while attempting to save a new entry using the New Entry Form in DataTable, stating that the variable "

I have encountered an issue with a table that includes a bootstrap modal containing a form. After filling out the form and saving the data or closing the modal, I want to refresh the table data. However, I am receiving the following error: TypeError: c i ...

Ways to incorporate an image into Vue Component CSS inline styles with a non-relative path

Seeking guidance on how to include an image in my Component code <template> <div class="example-class"> <p>Test</p> </div> </template> <style> .example-class { background-image: url("HOW to include ...

Axios transforms into a vow

The console.log outputs of the api and axios variables in the provided code are showing different results, with the state axios becoming a Promise even though no changes were made. The 'api' variable holds the normal axios instance while 'ax ...

Maximum number of days that can be selected with Bootstrap Datepicker

I currently have a datepicker set with the multidate option and I am looking to specify a maximum number of days that users can select, say 5 days. Once a user has selected 5 days, any additional days should become disabled dynamically. How can this be a ...

an occurrence of an element being rendered invisible, within an instance of an element being rendered as flexible,

I am trying to create a button that will show a list of elements. Within this list, there is another button that can be used to either close the list or hide it entirely. However, for some reason, my code is not functioning properly. let btn1 = documen ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...

Arranging information within an ExpansionPanelSummary component in React Material-UI

https://i.stack.imgur.com/J0UyZ.png It seems pretty clear from the image provided. I've got two ExpansionPanelSummary components and I want to shift the icons in the first one to the right, next to ExpandMoreIcon. I've been playing around with C ...

Oh no! It seems like the build script is missing in the NPM

https://i.stack.imgur.com/el7zM.jpg npm ERR! missing script: build; I find it strange, what could be causing this issue? Any suggestions? I have included the fullstack error with the package.json. Please also review the build.sh code below. Fullstack err ...