Utilizing Vue.js to share a single array of data across two distinct input lists

For a clearer understanding of my requirements, I have put together a demo on JSFiddle: https://jsfiddle.net/silentway/aro5kq7u/3/

The code snippet is presented below:

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="mainApp" class="container-fluid">

    <p>This section contains the main list.</p>
    <div class="main-list" v-for="(q, index) in questions">
        <input type="checkbox" 
               v-bind:id="'question-' + index" 
               v-bind:value="{id: index, property: false}"
               v-model="answers">

        <label v-bind:for="q">{{q}}</label>
    </div>

    <p>Next, we have a list displaying the selected elements from the above list.</p>
    <ul class="selected-list" v-for="(a, index) in answers" :key="a.id">
        <li>{{questions[a.id]}} <input type="checkbox"
                                       v-bind:id="'answer-' + index" 
                                        v-bind:value="true"
                                        v-model="a.property">
        </li>

    </ul>

    <p>Below is the array showing the answers for debugging purposes: {{answers}}</p>

</div>

<script>
var mainApp = new Vue({
                el: '#mainApp',
                data: {
                    questions: [
                        "Who are you ?",
                        "Who, who?",
                        "You know my name?",
                        "Look up my number"
                    ],
                    answers: []
                }
});

</script>
    

I aim to present an initial list of questions with individual checkboxes. The chosen questions should be saved in an array named "answers". From these selections, I wish to create another checklist where each item has its checkbox for a specific property (either true or false). It is crucial that this associated property is saved within the same "answers" array as the primary input.

In the current implementation, modifying a box in the secondary list alters the shared data array ("answers"), but also results in the corresponding answer being deselected in the first list.

Your assistance in resolving this issue would be highly appreciated.

Answer №1

It's quite challenging to follow your wording, but I attempted it nevertheless. My suggestion would be to organize selected questions and answers in separate arrays and utilize a computed property to combine them effectively. Take a look at this quick demonstration on JSFiddle for reference: https://jsfiddle.net/crswll/d8e1g750/21/

new Vue({
  data: {
    questions: [{
        id: 1,
        question: 'What the heck 1?'
      },
      {
        id: 2,
        question: 'What the heck 2?'
      },
      {
        id: 3,
        question: 'What the heck 3?'
      },
      {
        id: 4,
        question: 'What the heck 4?'
      },
      {
        id: 5,
        question: 'What the heck 5?'
      },
    ],
    selectedQuestions: [],
    selectedAnswers: [],

  },
  computed: {
    answers() {
      return this.selectedQuestions.map(id =>
        this.questions.find(question => question.id === id)
      )
    },

    selectedAnswersSimpleList() {
      return this.selectedAnswers
        .map(id => this.questions.find(question => question.id === id))
        .map(question => question.question)
    }
  },
}).$mount('#app')

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

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

Include parameters for a pagination system

I have a script that fetches data from my database and generates pagination. Everything is working fine, but now I want to include a conditional statement to differentiate the user level as New, Current, or Renewing client. I've already set up some s ...

Error encountered with Firebase Modular SDK V9.0.0+: Issue with undefined firebase property 'apps' causing TypeError

Encountered an error while attempting to run my next.js app. Despite trying various methods, I have been unable to resolve it. The version of Firebase I am using is 9.0.1 Server Error TypeError: Cannot read property 'apps' of undefined The error ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Is there a way to determine the model name programmatically within a Sails.js lifecycle callback?

Two models are present, with one model extending from the other. For all sub-models to inherit a lifecycle callback defined in BaseObject, I need a way to retrieve the name of the model being acted upon within the callback. This information is crucial for ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

PHP: Eliminating Line Breaks and Carriage Returns

My content entered into the database by CKEditor is adding new lines, which poses a problem as I need this data to be rendered in JavaScript as a single line of HTML. Within my PHP code, I have implemented the following steps: $tmpmaptext = $map['ma ...

Eliminating unnecessary whitespace between the bottom of the document and an element

I have a HTML page that when scrolled should limit scroll to the document height. It must not exceed the bottom of an element. Here is a screenshot for better understanding: https://i.stack.imgur.com/RaVg8.jpg The scrolling should be limited after the En ...

Is it necessary to alter the number of rows or columns in the table?

I'm having an issue with my code where the table is not changing the number of rows based on the selected input option. It seems to only read the first value of the select id and does not update the rows accordingly. Can someone help me identify the m ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

Tips for incorporating inline styling into the body element

Can someone help me with adding inline style to the body element using jQuery? I want to set the background color to white (#FFFFFF). Your assistance would be highly appreciated. Thank you! ...

Is async/await necessary even if the outcome is not important to me?

Imagine I have an API call that performs X and I convert it into asynchronous code using async/await: export default async (req: NextApiRequest, res: NextApiResponse) => { let success = await sendEmail({ //... }); return res.status(200) ...

Warning: MaxListenersExceededNotification may occur during the installation or creation of Node.js projects on macOS

Encountering a warning message while attempting to set up or generate Node.js projects on macOS (darwin): (node:80101) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxList ...

building responsive servers within Gulp using connect

Can I validate the availability of a server port before creating it using Gulp? Currently, this is my approach: /** * Start LiveReload Server */ gulp.task('connect', function() { var connect = require('connect'), app = ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

File is indicating a status of 200 ok, however it is not being displayed on the screen (node.js, expressjs)

I'm trying to display a video file in the browser and access it like an API on my front end. My goal is to have my front end call the video using a simple <video> tag. <video> <source ="video/randomfile.mov" type="video/mov"> < ...