SoFunction
Updated on 2025-04-04

Detailed explanation of the global usage of Vue mixin

Post it firstOfficial definition

I personally think that global mixin is to add some common instances (methods, filters and so on) to all Vue files.

Use scenarios: currency unit, time format. If these are used on the page, the code will be repeated a lot, so mixing these instances globally will reduce the amount of code and be more maintainable.

ex:

step1: Define first

const mixin = {
 methods: {
  /**
    * Format time
    * @param {string|number|object|Array} dateTime - Time, can be a string, timestamp, object representing time, Date object, or an array representing time
    * @param {string} [fmt] - Format
    * @returns {string} Returns the formatted date and time, default format: January 11, 2018 15:00
    * @see [momentjs]{@tutorial /}
    */
  formatDate (dateTime, fmt = 'YYYYY M month DD day HH:mm:ss') {
   if (!dateTime) {
    return ''
   }
   ('zh-CN')
   dateTime = moment(dateTime).format(fmt)
   return dateTime
  }
 }
}export defaullt mixin

step2: In the file

import mixin from './mixin'
(mixin)

Global mixin is .mixin has no s

step3: In your vue file, you can use the things defined in the mixin, for example

 

data() {
  return {
   userName: "Wait for you",
   time: (new Date()),
   arr: [1,2,3,4,5,'Word'],
   result: []
  }
 }

The time in the data source data of this vue file is the method of incoming references.

Using the method in mixins

Set up routing

// src/router/
import Vue from 'vue'
import Router from 'vue-router'
(Router)

export default new Router({
 mode:'history',
 routes: [
  {
   path:'/',
   redirect:'/index'
  },
  {
   path: '/about',
   name: 'About',
   component:resolve => require(['@/pages/About'],resolve)
  },
  {
   path: '/index',
   name: 'Index',
   component:resolve => require(['@/pages/Index'],resolve)
  },
  {
   path: '/product',
   name: 'Product',
   component:resolve => require(['@/pages/Product'],resolve)
  }
 ]
})

The page calls the loadPage method in mixins

<p @click="loadPage('Index')">Index</p>

The Index page is as follows

// src/pages/Index
&lt;template&gt;
 &lt;div&gt;
  &lt;p&gt;This isindexpage&lt;/p&gt;
  &lt;p @click="loadPage('Index')"&gt;Index&lt;/p&gt;
  &lt;p @click="loadPage('About')"&gt;About&lt;/p&gt;
  &lt;p @click="loadPage('Product')"&gt;Product&lt;/p&gt;
 &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
 export default{

 }
&lt;/script&gt;
&lt;style&gt;

&lt;/style&gt; 

At this point, the global inclusion is completed, and readers who are interested can also try partial inclusion (mainly used for later code maintenance).

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.