Replace Vue's mixin function

Is it possible to overwrite one of npm's mixins that is used within a component with a local mixin?

I have a component from an npm package located in

node_modules/somePackageName/components/footer.vue
which uses a mixin from
node_modules/somePackageName/mixins/popup.js

The popup.js file contains the following method:

methods: {
  setPopupActiveStatus (val, blur = true) {
    const isVisible = false
  }
},

And I am trying to override this behavior from my App.vue file where I use the footer.vue component like so:

methods: {
  setPopupActiveStatus (val, blur = true) {
    const isVisible = true
  }
},

However, my attempt to override the mixin is not working as intended.

==== UPDATE ====

Here is how I managed to resolve my issue based on the solution provided by @Estradiaz:

https://i.sstatic.net/w7TWR.png

Answer №1

When merging mixin and component options:

When a mixin and the component both have overlapping options, they will be combined using specific strategies:

  • Data objects are merged recursively, giving priority to the component's data in case of conflicts.

  • Hook functions with the same name are merged into an array so that all of them are executed. Mixin hooks precede the component's own hooks.

  • Methods, Components, and Directives are merged into the same object. Conflicting keys in these objects prioritize the component's options.

Here is an example of a method provided by both a component and a mixin:

var mixin = {
  methods: {
    foo: function () {
      console.log('Mixin Message')
    },
  }
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    foo: function () {
      console.log('Component Message')
    },
  }
})

vm.foo() // => "Component Message"

And here is an example on codesandbox

Therefore, you can effectively "override" the mixin by simply providing a method with the same name on the component as it will take precedence

Answer №2

Expanding Vue Functionality

If you're looking to enhance your current Vue component with a custom method, you can achieve this using the Vue.extend function. Vue simplifies the process of cloning/extending components by utilizing the extends option:

Option/ Composition - extends

import SourceComponent from 'node_modules/somePackageName/components/footer.vue'
export default {
   name: "override",
   extends: SourceComponent,
   methods: {
      thatActualMethodBehaviour(){}
   }
} 

Vue.extend

// This can be either a Function or an Object
import SourceComponent from 'node_modules/somePackageName/components/footer.vue'
if(typeof SourceComponent === 'function'){
  export default SourceComponent.extend({
      methods: {thatActualMethodBehaviour(){}}
  })
} else {
  export default Vue.extend(SourceComponent).extend({
      methods: {thatActualMethodBehaviour(){}}
  })  
}

Option/ Composition - mixins

// Mixins must be an Object
import SourceComponentOption from 'node_modules/somePackageName/components/footer.vue'
if(typeof SourceComponent !== 'function'){
  export default Vue.extend({
      mixins: [SourceComponentOption],
      methods: {thatActualMethodBehaviour(){}}
  })
}

The Path to Expansion

import SourceComponentOption from 'node_modules/somePackageName/components/footer.vue'
export default Object.assign({}, SourceComponentOption, {methods: Object.assign({}, SourceComponentOption.methods, {thatActualMethodBehaviour: function(){}}))

TypeScript Integration: vue-property-decorator

import {Vue, Component} from 'vue-property-decorator'
import SourceComponent from 'node_modules/somePackageName/components/footer.vue'
@Component<CustomComponent>({...hooks})
export default class CustomComponent extends SourceComponent{
   methods: thatActualMethodBehaviour(){}
}

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

Refresh the view in AngularJS following a successful $http.get request

I have a <ul> in my HTML view that is populated based on a $http.get request. HTML: <div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl"> <h1>Sample Records</h1> <ul> <li class= ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...

Save the array as a variable in your JavaScript code so that you can easily access it

I am currently working on generating a list only when a specific page is visited using JS/jQuery. I then need to be able to access this list when navigating to other pages and retrieve the variables within it. How can I effectively store this list? Initia ...

What is the best way to ensure that JavaScript is loaded in a specific sequential order?

I'm having trouble ensuring that JS files load in the correct sequence, despite my efforts to research async and defer on various platforms. This is the structure of my code: <script src="lang.js"></script> <!--loading either ...

Text below a stationary header

I need some help with my code using material-ui-next beta.30. The issue I am facing is that the content within mui.Paper is appearing behind the AppBar instead of below it. Here's my current setup: import * as React from 'react'; import * a ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

Is there a JavaScript function available to remove comments from previously commented HTML code?

<div id="div1">bar</div> JQuery function addComment(element){ element.wrap(function() { return '<!--' + this.outerHTML + '"-->'; }); } addComment($('#div1')); Looking for assistance in unc ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

Getting parameter names (or retrieving arguments as an object) within a method decorator in TypeScript: What you need to know

I am currently working on creating a method decorator that logs the method name, its arguments, and result after execution. However, I want to implement a filter that allows me to choose which parameters are logged. Since the number and names of parameter ...

Nuxt3: sending a user's submitted value from a registration form

I'm facing an issue in my Nuxt3 application where I need to pass the input value from an email field in a child component (SignForm.vue) to the parent component (signup.vue) for user registration. signup.vue <script setup> const props = { ...

Library for creating custom password input fields with a text type

We are currently facing an issue on our website where autofill is not working correctly due to having two password input fields - one for login and one for the password. Browsers are unable to remember the login information and paste the password into th ...

Utilizing the power of Material-UI with React in conjunction with Python-Django: A comprehensive

I am seeking guidance on implementing React with Material UI components in my web application. The technologies I have utilized in multiple projects include: Materialize CSS, Javascript, Jquery. The technologies I wish to explore for future projects are ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...

The custom pagination feature in Addsearch UI always default to displaying the first page of search

I am currently using addsearch-ui version 0.7.11 for my project. I have been attempting to integrate a customized pagination function based on this example template. However, I have encountered an issue where the arrow buttons always navigate to the first ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...