[Vuejs]-How to reuse a SFC Vue component instance in different components?

0👍

There are two ways to do this-

  1. Globally import the component in the main.js file and use on any page freely. i.e.-
    import Vue from "vue";  
    import Player from "@/components/Player.vue";  
    Vue.component("AppButton", AppButton); 
  1. Create a mixin named playerMixin.js inside the mixins directory.
    Import the Player component inside that mixin and import that mixin in all pages.
    The mixin code should look like this-

playerMixin.js

import Player from "@/components/Player.vue";

export const playerMixin = {
  data() {
    // any data properties related to player functionalities 
  },

  components: {
    Player,
  },

  methods: {
    // any methods related to player functionalities
  }
}

Now, you can use this mixin on any page, like this-

AnyPage.vue

import { playerMixin} from "@/mixins/playerMixin.js";

export default {
  name: "AnyPage",
  mixins: [playerMixin],
}

The main benefit of using mixin is that not only components will be imported once but the common functionality of Player which is the same for every page like passing props, and methods like play, a pause can be written once and can be used by any page.

To understand more about mixin, read this.

Leave a comment