Trouble encountered when executing Vue code within Nuxt SPA due to a conflicting vmodel on the same element

I am encountering an issue while trying to run a codepen within a Nuxt app that is set up as a SPA.

Here is the codepen that works: https://codepen.io/jjelic/pen/yevNLZ

However, when I add this code to my filters/index.vue file, I get an error:

The line 'value="row.qty * row.price | currencyDisplay"' conflicts with v-model on the same element due to internal value binding.

  • The line ':value="row.qty * row.price * row.tax / 100"' also conflicts with v-model because of the same reason.
  • List item

I am puzzled why this codepen works fine online but causes conflicts with Vue/Nuxt. Is there a workaround available to resolve this issue?

Below is my code snippet:

Vue.filter('currencyDisplay', {
// model -> view
read: function (val) {
    if (val > 0) {
        return accounting.formatMoney(val, "$", 2, ".", ",");
    }
},
// view -> model
write: function (val, oldVal) {
    return accounting.unformat(val, ",");
}
});

Vue.directive('sortable', {
twoWay: true,
deep: true,
bind: function () {
    var that = this;

    var options = {
        draggable: Object.keys(this.modifiers)[0]
    };

    this.sortable = Sortable.create(this.el, options);
    console.log('sortable bound!')

    this.sortable.option("onUpdate", function (e) {
        that.value.splice(e.newIndex, 0, that.value.splice(e.oldIndex, 1)[0]);
    });

    this.onUpdate = function(value) {
        that.value = value;
    }
},
update: function (value) {
    this.onUpdate(value);
}
});

var vm = new Vue({
el: '#app',
data: {
    rows: [
        //initial data
        {qty: 5, description: "Something", price: 55.20, tax: 10},
        {qty: 2, description: "Something else", price: 1255.20, tax: 20},
    ],
    total: 0,
    grandtotal: 0,
    taxtotal: 0,
    delivery: 40
},
computed: {
    total: function () {
        var t = 0;
        $.each(this.rows, function (i, e) {
            t += accounting.unformat(e.total, ",");
        });
        return t;
    },
    taxtotal: function () {
        var tt = 0;
        $.each(this.rows, function (i, e) {
            tt += accounting.unformat(e.tax_amount, ",");
        });
        return tt;
    }
},
methods: {
    addRow: function (index) {
        try {
            this.rows.splice(index + 1, 0, {});
        } catch(e)
        {
            console.log(e);
        }
    },
    removeRow: function (index) {
        this.rows.splice(index, 1);
    },
    getData: function () {
        $.ajax({
            context: this,
            type: "POST",
            data: {
                rows: this.rows,
                total: this.total,
                delivery: this.delivery,
                taxtotal: this.taxtotal,
                grandtotal: this.grandtotal,
            },
            url: "/api/data"
        });
    }
}
});

    <template>

      <div class="panel-body" id="app">
        <table class="table table-hover">
            <thead>
            <tr>
                <th style="width: 20px;">No.</th>
                <th>Description</th>
                <th style="width: 80px;">Qty</th>
                <th style="width: 130px;" class="text-right">Price</th>
                <th style="width: 90px;">Tax</th>
                <th style="width: 130px;">Total</th>
                <th style="width: 130px;"></th>
            </tr>
            </thead>
            <tbody v-sortable.tr="rows">
            <tr v-for="row in rows" track-by="$index">
                <td>
                    {{ $index +1 }}
                </td>
                <td>
                    <input class="form-control" v-model="row.description"/>
                </td>
                <td>
                    <input class="form-control" v-model="row.qty" number/>
                </td>
                <td>
                    <input class="form-control text-right" v-model="row.price | currencyDisplay" number data-type="currency"/>
                </td>
                <td>
                    <select class="form-control" v-model="row.tax">
                        <option value="0">0%</option>
                        <option value="10">10%</option>
                        <option value="20">20%</option>
                    </select>
                </td>
                <td>
                    <input class="form-control text-right" :value="row.qty * row.price | currencyDisplay" v-model="row.total | currencyDisplay" number readonly />
                    <input type="hidden" :value="row.qty * row.price * row.tax / 100" v-model="row.tax_amount | currencyDisplay" number/>
                </td>
                <td>
                    <button class="btn btn-primary btn-xs" @click="addRow($index)">add row</button>
                    <button class="btn btn-danger btn-xs" @click="removeRow($index)">remove row</button>
                </td>
            </tr>
            </tbody>
            <tfoot>

            <tr>
                <td colspan="5" class="text-right">TAX</td>
                <td colspan="1" class="text-right">{{ taxtotal | currencyDisplay }}</td>
                <td></td>
            </tr>
            <tr>
                <td colspan="5" class="text-right">TOTAL</td>
                <td colspan="1" class="text-right">{{ total | currencyDisplay }}</td>
                <td></td>
            </tr>
            <tr>
                <td colspan="5" class="text-right">DELIVERY</td>
                <td colspan="1" class="text-right"><input class="form-control text-right" v-model="delivery | currencyDisplay" number/></td>
                <td></td>
            </tr>
            <tr>
                <td colspan="5" class="text-right"><strong>GRANDTOTAL</strong></td>
                <td colspan="1" class="text-right"><strong>{{ grandtotal = total + delivery | currencyDisplay }}</strong></td>
                <td></td>
            </tr>
            </tfoot>
        </table>
        <button @click="getData()">SUBMIT DATA</button>
        <pre>{{ $data | json }}</pre>
    </div>

        </template>

Answer №1

When using Nuxt, Vue 2 is utilized. However, in your codepen example, Vue 1 is linked.

If you are trying to use v-model with a value attribute, it will not work. You must remove the value attribute where you have v-model and instead set that value into the field that v-model references. Check out the documentation for more information.

v-model will ignore the initial value, checked, or selected attributes on form elements. It always considers the Vue instance data as the source of truth. Therefore, you should declare the initial value within the data option of your component in JavaScript.

<input type="hidden" :value="row.qty * row.price * row.tax / 100" v-model="row.tax_amount | currencyDisplay" number/>

This means that your `row.tax_amount` should be set with the value calculated inside JavaScript:

row.qty * row.price * row.tax / 100

The updated code should exclude the :value attribute like this:

<input type="hidden" v-model="row.tax_amount | currencyDisplay" number/>

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 methods can I use to identify the startup folder of a Node application in macOS?

I'm in the process of creating a versatile NodeJS server/app that is packaged as a prebuilt binary using pkg (https://www.npmjs.com/package/pkg) for Windows, Mac, and Linux. Upon initialization, the app needs to generate a default config.json file in ...

Is it possible to effectively determine a roster of event names while implementing the defineEmits() feature in Vue 3?

Within a reusable component, my goal is to develop a simple function that creates proxies for props in order to bind them to child components. These proxies will maintain their own internal value and be initialized with the default prop value, which may be ...

What is the best way to ensure that a component is fully rendered before receiving an API callback?

I have a dilemma where I receive data from an API and store it in a property named source within the created method. However, I am encountering difficulties in the render function when trying to transfer some of the data from source to the participants pro ...

Show the id value of the event triggered by eventclick

I am currently attempting to retrieve the id of the event so that I can remove it from the database. My approach involves using eventClick, where a dialog pops up when the user clicks an event prompting them to remove it. In order to proceed with this oper ...

Displaying specific choices depending on the previous selection made

I am facing an issue in Laravel where I have two selection options, and one depends on the other. Despite multiple attempts, I haven't been able to resolve it. The database structure is as follows: companies id title channels id company_id title I ...

Evaluate a program to identify prime numbers

I am currently working on a JavaScript program that utilizes recursion to determine whether an input is a prime number or not. Within my code, I've defined the isPrime function. The base cases are set to return false when x==1 and true for x==2, cons ...

Retrieving chosen row data in Angular 6 Material Table

I am attempting to send the value of a selected row from one component to another upon clicking a button. However, in this particular example, I'm unsure where to obtain the selected row values and how to pass them on button click. After that, routing ...

Store fresh JSON information in a newly created JSON document

As someone new to JavaScript, I really appreciate your assistance. I'm utilizing the randomuser.me API to generate a list of users, but the names are all in lowercase. With the help of someone else, I managed to capitalize the names using a script. N ...

The NuxtLink feature in Nuxt3 doesn't automatically refresh the layout CSS when the route changes

The functionality described in the code snippet below is quite straightforward. When a user visits the /blog route, the layout is switched to the blog layout which has a different header style. Similarly, the homepage has its own unique header style. Howev ...

Variations in how words are organized within a sentence

Can you help me devise an algorithm to identify all possible combinations of word groupings in a sentence without changing the order of the words? For example, for the sentence "the test case phrase," the various combinations would include: ['the te ...

What is the process for importing a node module in React-Kotlin?

After creating my app using the create-react-kotlin-app command, it loaded successfully in Chrome. I then installed the React Material UI package via NPM without any issues. However, I am now facing the challenge of incorporating the Material UI module int ...

How to retrieve the index of an object in Angular using ng-repeat

I am working with an object structured like: { "2015": ["path",0, 0], "2016": ["path",0, 0], "2017": ["path",0, 0], "2018": ["path",0, 0], } My goal is to display this information in a grid format using ng-repeat. The desi ...

A guide to creating custom form controls with validation using pseudocode in Bootstrap

I am working with a Bootstrap form and I want to display a green check mark in the input box when both the required fields are filled and they match my specified pattern. .form-control.is-valid, .was-validated .form-control:valid { border-color: var(-- ...

Calculating interest rates in Javascript: A guide to determining values using two separate rates

I am currently working on an earnings calculator function EarningsCalculator.prototype.calculateEarning = function (interestRate, investmentAmount) { var earningHistory = {}; var currentInvestment = investmentAmount; for (var year = 1; year & ...

The .Remove() method appears to be ineffective in MongoDb

I keep getting an error stating that Contact.remove() is not a function. My goal is to remove a specific contact by passing its ID. const DeleteContact = asyncHandler(async (req, res) => { const contact = await Contact.findById(req.params.id); ...

Incorporating font-awesome icons into your project using webpack

I have a Bootstrap template and I am trying to integrate it with FountainJS. I have included all the SCSS files from the template and everything is working fine. Now, I am trying to include Font Awesome, so I used npm install font-awesome --save and added ...

Retrieving data from slots in Vue.js components without the need to declare templates externally

Creating Menu components for frameless windows, but unsure how to bind events into slot. I want to build a structure like this: in WindowBar.vue <template> <div> <app-menu-bar> <app-menu label="File"></app- ...

I attempted to post a collection of strings in ReactJS, only to receive a single string response from the Web

I was troubleshooting an issue where only one string from ReactJS was being sent to WebApi instead of an array of strings. Below is the ReactJS code snippet I used: import React, { useState } from "react"; import axios from "axios"; e ...

What is the best way to incorporate correct reference logic when utilizing Joi validation?

I am currently working on designing a straightforward schema to validate inputted number ranges. The condition is that the start value should be less than the end value, and conversely, the end value must be greater than the start value. Below is the sche ...

Is it possible to run a local file on a localhost server in Sublime Text 3 with the help of the SideBar

I am attempting to host my index.html file on a localhost server in order to utilize an angular routing directive. Despite following the steps, I am encountering issues. //sidebarenchancements.json { "file:///C:/Users/Jdog/Desktop/projects/Calibre/soci ...