Changing data in vue

I am utilizing a mixin in my Vue code to both add and override data properties. While I can successfully add new data, I am facing issues when trying to override existing data values. Below is a snippet of the code:

var mixin = {
    data: function() {
        return {
            foo: 'boo',
            test: 'blah'
        }
    }
}

var vm = new Vue({
  el: '#vue-instance',
  mixins: [mixin],
  data: function() {
    return {
        foo: 'bar'
    }
  }
});

Upon running this code, 'test' retains its value as 'blah', however, 'foo' remains stuck at 'bar'. Is there any way to make a mixin override existing Vue data alongside adding new data?

For reference, here is a link to a live example on JSFiddle:

https://jsfiddle.net/8v9sfxok/

Answer №1

Extracted from the mixins documentation:

When dealing with options that require object values, they will be combined into a single object. The component’s options will prevail in cases where there are conflicting keys within these objects

(highlight mine).

If you wish to use a different merging approach, you have the option to define one.

Answer №2

To work around this issue, you can create a method within your mixin and then call that method from your template:

HTML:

<div id="my-vue-app">
  <p>
  {{getFoo()}}
  </p>
  <p>
  {{test}}
  </p>
</div>

JavaScript:

var myMixin = {
    data: function() {
    return {
      foo: 'baz',
      test: 'blah'
    }
  },
  methods: {
    getFoo: function () {
        return 'baz';
    }
  }
}

var vm = new Vue({
  el: '#my-vue-app',
  mixins: [myMixin],
  data: function() {
    return {
      foo: 'bar'
    }
  }
});

Check out the JSFiddle example here.

Answer №3

A point that has been brought up is that mixins are unable to alter pre-existing data. To work around this limitation, I transformed my initial component into a "base" component and utilized the "extends" feature in a separate component to modify the existing data.

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

The robots.txt file in Nuxt.js allows for multiple disallow directives for each user agent

With the Nuxt module called nuxt-robots, how can I set up multiple disallow rules per user agent? Currently, my configuration looks like this: robots: () => { return { UserAgent: '*', Disallow: '/search/', Si ...

The error message states, "undefined cannot be used as a function."

For testing purposes, I am running checks on my Service using httpBackend. Specifically, I am focusing on a simple get request that needs to be tested for the response code. However, despite my efforts, I keep encountering this error: TypeError: undefined ...

Fixing Timezone Issue in VueJs 3 with Axios POST Request

Having an issue with axios. In my application, I have an input field for datetime-local. When I select a date and time, the displayed time is correct (e.g., selecting 10:00 shows as 10:00), but when calling a function using axios.post, the request sends th ...

The Best Approach for Angular Google Maps Integration

I'm diving into Angular for the first time while working on a project that requires advanced mapping functionality like clustering, routing, road routing, paths, directions, polygons, events, drawing on maps, info windows, markers, etc. After some re ...

Are trailing commas or missing keys acceptable in JavaScript object notation?

I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code. function init() { v ...

Sub-menu disappears upon resizing the screen

Currently, I am working on creating a unique responsive navigation system that transforms into a 100% width pulldown menu for mobile devices. To achieve this functionality, I have implemented some JavaScript code that hides any open sub-menu items when the ...

Adding Data to a Database Using Ajax with PHP

I am trying to use Ajax to insert data into a database, but I keep encountering this error: Uncaught ReferenceError: insertData is not defined at HTMLInputElement.onclick (Modal.php:105) Error screenshot: https://i.sstatic.net/AmXka.jpg The HTML and ...

Express.js routes are malfunctioning with jade/pug, causing frequent crashes and routing errors

Here is the code for my contact router: var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('contact'); }); module.exports = rou ...

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 ...

I have a question about CSS selectors: How can I change the font color of a parent <li> element when the child

After struggling for hours, I'm finally throwing in the towel on this issue. I have an unordered list with no background at the top level and text color of #fff. When rolled over, the background turns #fff and the text color turns #000. The child ul ...

The scrolling speed of the mousewheel in Firefox is notably slower compared to that of Google Chrome

Kindly review this sample link: When I test the above example in Chrome and scroll using the mouse wheel, the page moves up by 100px each time. The Y position is displayed as well. However, if I try the same page in Firefox 26.0 and scroll with the mouse ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

Building upcoming records in Firestore

Seeking advice on the best approach for managing future milk orders in my Vue.js application. In this app, customers can subscribe to order milk 1, 2, or 7 times a week for a specific period (e.g. 90 days). The challenge lies in determining how to handle ...

Searching for the way to access the values of a nested object's ref in Vue JS?

Within my Vue data object, I store a reference to a structure called Plot. It has properties for length, width, and acreage. interface Plot { length: number, width: number, acreage: number } const model = { plot: ref<Plot[]>([]), }) When fe ...

Retrieve information by performing a search query on two tables in Laravel and VueJS, using specific conditions

Is there a way to retrieve data from both the Employee and Company tables based on a search by Company name rather than Company Id? These tables have a one-to-many relationship. The current search functionality is working well, but any assistance on implem ...

A guide to incorporating suspense and dynamic components into Vue 3

I have encountered an issue with using suspense in my code. I am importing four different components asynchronously and when I switch between them by clicking buttons, the loading slots in suspense only show for the first time. It doesn't work when I ...

PhantomJS 2.0.0 not delaying page loading

In the script provided, there is an array of URLs called links. The function gatherLinks() is designed to collect additional URLs from the sitemap.xml file related to the ones in the links array. Once the number of URLs in the links array reaches a certain ...

Issues persist with the Vue model not being updated

Whenever I attempt to update the model data of my custom text-area component this.message='<span id="foo">bar</span>, the text and html do not appear in the htmltextarea tag as expected. However, I can see the update being applie ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

What is the best way to transfer form input data from a child component to the parent component in React?

Recently delving into the world of React, I decided to experiment with forms. My project idea was straightforward - create a form component with input fields that, upon clicking submit, would pass the input values to the parent component ('App') ...