The functionality of V-model is hindered when implementing Bootstrap Tokenfield

While working with Vue and Bootstrap Tokenfield, I encountered an issue where v-model was not functioning as expected.

Let's say I have the following array:

index variant_options
1 aaa
2 sss

If I remove index 1, the result of index 1 should be "sss" but it still shows "aaa".

<div class="card" v-for="(variant, index) in form.variants" :key="index">
<div class="card-body"> <span class="float-right" style="cursor: pointer" @click="deleteVariant(index)">
                                                            X
                                                        </span>
    <div class="row">
        <div class="col-md-4">
            <label for="weight">Variant Type {{ index + 1 }} </label>
            <div class="input-group">
                <input type="text" id="variant_type" class="form-control" v-model="
                                                                            variant.variant_type
                                                                        " @keyup="tokenField()" placeholder="Input variant type. E.g: Color" name="name" required autofocus /> </div>
        </div>
        <div class="col-md-8">
            <label for="weight">Variant Options {{ index + 1 }}</label>
            <div class="input-group">
                <input type="text" id="variant_options" autofocus="true" v-model="
                                                                            variant.variant_options
                                                                        " @mouseover="
                                                                            tokenField()
                                                                        " placeholder="Input variant options. E.g: Blue, Brown," class="
                                                                            form-control
                                                                            variant_options
                                                                        " /> </div>
data() {
    return {
        form: new Form({
            variants: [
                {
                    variant_type: '',
                    variant_options: '',
                },
            ],
        }),
    };
},
methods: {
    tokenField() {
        $('.variant_options').tokenfield({
            showAutocompleteOnFocus: true,
        });
    },
    addVariant() {
        if (this.form.variants.length <= 1) {
            this.form.variants.push({
                variant_type: '',
                variant_options: '',
            });
        } else {
            this.error = 'You can only add 2 type of varians';
            $('#errMsg').show();
        }
    },
    deleteVariant(index) {
        this.form.variants.splice(index, 1);
        $('#errMsg').hide();
    },
}, // methods:

Answer №1

It is crucial to avoid using the index variable from a v-for loop as the :key, especially when dealing with elements such as <input> and performing actions like adding, removing, or sorting items.

To understand more about maintaining state in Vue.js, refer to the documentation - Maintaining State

Although not explicitly stated in the docs, utilizing the index as the :key attribute behaves similarly to not using a key at all. The purpose of a key is to establish a unique relationship between each item in the loop and the corresponding DOM element created for it, which cannot be achieved by the index alone.

The key should remain stable and unique across all list items. In cases where data does not naturally provide such a key (e.g., editable properties like variant_type and variant_options), generate your own artificial key. There are various methods available in JavaScript for generating unique IDs.

For example, you can use a "running index" approach:

data() {
    return {
        nextId: 1,
        form: new Form({
            variants: [
                {
                    id: 0,
                    variant_type: '',
                    variant_options: '',
                },
            ],
        }),
    };
},
methods: {
    addVariant() {
        if (this.form.variants.length <= 1) {
            this.form.variants.push({
                id: this.nextId++,
                variant_type: '',
                variant_options: '',
            });
        } else {
            this.error = 'You can only add 2 types of variants';
            $('#errMsg').show();
        }
    },
}

Remember to include :key="variant.id" in the template to ensure proper identification of each item.

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 could be causing my div link to redirect to different content instead of the intended destination?

When creating a div to provide information about a course, including the price and a "Take Class" button that links to the purchase page, I encountered an issue where the link extends beyond the intended area. @import url(https://fonts.googleapis.com/cs ...

JavaScript Logic to Check if an Element is Hidden

I'm having trouble figuring out how to close an element when another element collapses. I've searched for solutions without success. My structure is updated using Bootstrap and JavaScript, but it doesn't function as expected. Specifically, ...

Updating data in a table upon submission of a form in Rails

In my Rails 3.2 application, I am displaying a table of results using the @jobs variable passed to the view from a SQL query. I want to add a button that will trigger a controller action when clicked. The action should perform some database operations and ...

Error in SO Embed Snippet Fiddle due to Bootstrap 4 JS Issue

Just wondering, any idea why the bootstrap 4 js is throwing this error: https://i.sstatic.net/J4Iq4.png when trying to embed the snippet? (No errors in the external Fiddle) Added tether.js but no luck (kept it commented). Switched to jQuery 2.2.1 on th ...

Increasing the values of id attributes in AngularJS

Here is an example of some HTML code: <tr ng-repeat="x in y"> <td> <div ng-attr-id="{{getId()}}"></div> </td> <td> <div ng-attr-id="{{getId()}}"></div> </td> <t ...

Using third-party libraries like jQuery, CSS, and JavaScript in your React project by directly importing them into the index.html file can be a more efficient approach compared

When working with React, is it advisable to import external JavaScript, jQuery, and CSS files into the index.html file in the public folder? Are there any potential performance implications associated with this practice? I have utilized some jQuery functi ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...

A step-by-step guide on making a list item clickable and redirecting to a URL using Vue.js

Utilizing vue.js, I have successfully configured a navigation bar with multiple list elements. However, I am seeking guidance on how to redirect one of the list elements to an external website, such as https://www.google.com/. Within my router file, each e ...

Eliminate forward slashes in MySQL queries within a Node.js environment

Here is the code snippet that I am working with. pool.getConnection(function (err, connection) { connection.query("delete from userFiles where type = 1 and typeId = " + taskId + " and fileName ...

Using JavaScript to load content with AJAX on skip links

Is there a way to prevent the error "loadWithAjax is not defined" from occurring while using the script below? addEventListener('click', function (ev) { if (ev.target.classList.contains('bpb')) { ev.preventDefault(); ...

Attempting to showcase a list of 4 concatenated items in a dropdown menu sourced from the database

I am attempting to concatenate and display 4 items in a dropdown list using AJAX. For example, the value in the dropdown list should appear as (127, CoilWt, 1, KGS) from the database. In the database, I am selecting select CODE_VALUE, CODE_DESC, CODE_SUB ...

Assign a value to a locally scoped variable within an iteration in Angular 2

Within my Angular code, I have the following HTML snippet: <span *ngIf="ControllerType?.AttributeID =='Controller Type'"> <select multiple name="ControllerType.Default" [(ngModel)]="Contro ...

Showing validation for arrays with multiple inputs using Ajax in the Laravel framework

Could someone please provide guidance on how to use ajax to display the JSON response of form validation messages in Laravel? Below are some of my form inputs: {!! Form::text('stories[0][subject]', null, [ 'class' => 'form-con ...

Is there a way to modify the value of an object in a Vuex store using actions in Vue.js?

I have data stored in an array within the state and I need to update a specific object. How can I change the value of the object with id 1 to true using Vuex actions? state.js const array=[] mutations.js storeArray(state, data) { state.array = data ...

Tips for efficiently sorting a string array in JavaScript

Looking to sort an array in a specific numerical order? Check out this example: const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'] If you're running into issues when ...

Save an HTML5 canvas element as a picture using JavaScript and specify the file extension

Is there a way to save an Html5 canvas element as an image file using Javascript? I've tried using the CanvasToImage library, but it doesn't seem to work for this purpose. You can view my current code on JsFiddle. <div id="canvas_container" ...

Is Next.js the Ultimate Serverless Rendering Tool with Cloudflare Workers?

I am currently using Next.js version 9 and I am interested in utilizing Next's serverless deployment feature by integrating my application with Cloudflare Workers. According to the documentation for Next.js, all serverless functions created by Next f ...

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

Looking to compare values within an ng-repeat loop?

I am trying to compare values within the context of an ng-repeat directive. Specifically, I need to compare the current value with the previous value in the array being iterated over by ng-repeat. For example, if my array contains the values [2,3], how can ...