Link the global to the Vue component

Is there a way to connect global filters, mixins, and additional features to a specific Vue Instance rather than the Vue object directly?

For instance

import Vue from 'vue.js'
import App from './app'
import demo from './mixins/demo'

Vue.mixin(demo)

const vm = new Vue({
  router,
  render: h => h(App).$mount('#app')
})

What is the process for linking this mixin to vm instead of the Vue object if there are multiple instances involved?

I attempted vm.mixin(demo) but it did not yield the intended results

Answer №1

Your question seems a bit unclear, but it appears that you are interested in having multiple Vue root instances on the same page, each with its own set of global mixins, directives, filters, and so on.

Unfortunately, achieving this in Vue 2 is not straightforward. A good resource on this topic can be found in the Global API section of the Vue3 migration guide:

Vue 2.x includes various global APIs and configurations that impact Vue's behavior at a global level.

While this approach may be convenient, it presents some challenges. In Vue 2, there is no clear distinction of an "app." What we typically consider an app is essentially a root Vue instance created using new Vue(). All root instances created from the same Vue constructor share the same global configuration. This leads to:

The global configuration makes it tricky to have multiple "apps" sharing the same Vue instance, each with different global configurations.

This issue is particularly noticeable during testing. To address this, a createLocalVue() method was introduced in vue-test-utils, utilizing the Vue.extend global API to create a "subclass" of the base Vue constructor...

I have employed a similar approach below to demonstrate two separate Vue subclasses, each with its own global mixins and components. While this approach does work, it has some peculiarities (for instance, omitting the MyVue1.extend call can cause issues).

My overall takeaway from this experiment is that achieving this in Vue 2 is feasible but may involve challenges, suggesting that Vue 3 provides a more optimal solution to these issues...

const MyVue1 = Vue.extend()
const MyVue2 = Vue.extend()

MyVue1.mixin({
  methods: {
    mixinMethod: function() {
      return 'MyVue1'
    }
  }
})

MyVue1.component('my-component1', MyVue1.extend({
  template: '<div> Hello from my-component1: {{ mixinMethod() }} !</div>'
}))

MyVue2.mixin({
  methods: {
    mixinMethod: function() {
      return 'MyVue2'
    }
  }
})

MyVue2.component('my-component2', MyVue2.extend({
  template: '<div> Hello from my-component2: {{ mixinMethod() }} !</div>'
}))

const vm1 = new MyVue1({
  template: '<my-component1 />',
}).$mount('#app1')

const vm2 = new MyVue2({
  template: '<my-component2 />',
}).$mount('#app2')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app1"></div>
<div id="app2"></div>

Answer №2

Have you given it a shot?

import fooMix from './mixins/fooMix'
import barMix from './mixins/barMix'

const view1 = new Vue({
  router,
  mixins: [fooMix]
  render: h => h(App).$mount('#app1')
})

const view2 = new Vue({
  router,
  mixins: [barMix]
  render: h => h(App).$mount('#app2')
})

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

Begin counting when a particular div element is visible on the screen

I have a plugins.init.js file that contains a try-catch block which runs on page load. I am looking for a way to execute this code only once when the div with the class counter-value comes into view. Is there a method to achieve this? try { const count ...

MaterialUI makeStyles in NextJS causes custom css to revert back when the page is refreshed

Currently, I am working on a NextJS website with some unique styling applied through MaterialUI's makeStyles. Initially, everything looks perfect but then all the custom styling is reset on the second load. It seems to be related to the route, as it o ...

Adding Labels to Doughnut Charts in React using Chart.js 2.0

Currently, I'm exploring the world of data visualizations using react, react-chartjs-2, and chart.js version 2.2.1. While searching for a solution to my inquiry, I came across a potentially relevant answer on this link (specifically check out the upda ...

Error message in Node v12: "The defined module is not properly exported."

When trying to export a function in my index.js file, I encountered an error while running node index.js: module.exports = { ^ ReferenceError: module is not defined Is there a different method for exporting in Node version 12? ...

I'm curious if there is a method to indicate the specific destination within a separate file that the FS module in Node.js writes the data

Whenever I utilize the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});, it successfully writes the data to the JSON file. However, the problem is that the data is not inserted into the array where I actually need ...

Utilizing Typescript to troubleshoot linting issues

After running the TypeScript linter, I received the following error message: Do not use Function as a type. The Function type accepts any function-like value, providing no type safety when calling the function. This lack of specificity can lead to common ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Here's how you can use welding techniques to attach objects and incorporate fin-like structures in THREE

I am currently working on a project involving a rocket ship orbiting various planets. To achieve this, I have started by creating my own rocket ship object and am aiming to model it similarly to this design: https://kyleagnew.files.wordpress.com/2018/02/lo ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...

submit the contact form information to both the database and email for further processing and storage

Currently, I have the code for connecting to a database and mail.php. I am able to save contact form data in the database successfully, but I also want to send an email to my address which I'm unsure how to do with manage_comments.php. Here are the ...

Transform the page into a Matrix-inspired design

I decided to transform the appearance of my web pages into a stylish The Matrix theme on Google Chrome, specifically for improved readability in night mode. To achieve this goal, I embarked on the journey of developing a custom Google Chrome extension. The ...

Using JavaScript Regular Expressions to locate all prefixes leading up to a specific character

Consider a scenario where you have a string consisting of terms separated by slashes ('/'), like this: ab/c/def Your goal is to identify all the prefixes of this string up to a slash or the end of the string. For the given example, the expected ...

"execute loop in a strange and peculiar manner using JavaScript

Implement a loop to place markers on the map: for (i = 0; i <= 6; i++) { _coord = prj_markers[i]; alert(i); instance.set_marker(instance, provider, i, _coord, divBlock); } This code displays "0" in an alert once and executes instance.set_m ...

What is the process for setting a personalized title for error pages in Remix?

I'm currently working on setting up the 404 page for my Remix app, but I'm facing challenges when it comes to configuring the <title> meta tag for these pages. Within my root.tsx file, I have defined a MetaFunction and a CatchBoundary: exp ...

Tips for encapsulating a promise while maintaining the original return type

In my code, there is a function that utilizes an axios instance and is of type async function register(data: RegisterData): Promise<AxiosResponse<UserResponse, any>> export const register = (data: RegisterData) => api.post<UserResponse> ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...

How can I insert my URL into the webPDFLoader feature of LangChain platform?

I need help figuring out how to load a PDF from a URL using the webPDFLoader. Can someone explain how to implement this? Any assistance would be greatly appreciated. I am working on this task in nextjs. Where should I place the pdfUrl variable within the ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

Step-by-step guide on accessing and displaying a disc file within a webix application

I am a beginner in webix development and struggling to find documentation or help for my current issue. Within my webix application, I am trying to create a button (let's call it 'View Report') that when clicked will open a file from my loc ...

Comparing OLOO and OO in ReactJS for front-end web development

After reading Kyle's book, I found it to be extremely informative. However, I am a bit perplexed by the discussion in "You Don't Know JS: this & Object Prototypes". The series argues that the "Object Linking to Other Object" design pattern is cl ...