先貼上官方定義。
個人覺得全局mixin就是給全部Vue文件添加一些公用的實例(方法,過濾器and so on)
使用場景:貨幣單位,時間格式。這些如果在用到的頁面使用的話代碼會重復的很多,所以在全局混入這些實例會減少代碼量,可維護性也比較高。
ex:
step1: 先定義mixin.js
const mixin = { methods: { /** * 格式化時間 * @param {string|number|object|Array} dateTime - 時間,可以是一個字符串、時間戳、表示時間的對象、Date對象或者******表示時間的數組 * @param {string} [fmt] - 格式 * @returns {string} 返回格式化后的日期時間,默認格式:2018年1月11日 15:00 * @see [momentjs]{@tutorial http://momentjs.cn/} */ formatDate (dateTime, fmt = 'YYYY年M月DD日 HH:mm:ss') { if (!dateTime) { return '' } moment.locale('zh-CN') dateTime = moment(dateTime).format(fmt) return dateTime } }}export defaullt mixinstep2:在main.js文件里面
import mixin from './mixin'Vue.mixin(mixin)
全局混入是.mixin沒有s
step3:在你的vue文件里面就可以使用mixin里面定義好的東西比如
data() { return { userName: "等你", time: this.formatDate(new Date()), arr: [1,2,3,4,5,'文字'], result: [] } }這個vue文件的數據源data里面的time就是引用混入進來的方法。
使用mixins里的方法
設置路由
// src/router/index.jsimport Vue from 'vue'import Router from 'vue-router'Vue.use(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) } ]})頁面調用mixins里的loadPage方法
<p @click="loadPage('Index')">Index</p>Index頁面如下
// src/pages/Index<template> <div> <p>這是index頁面</p> <p @click="loadPage('Index')">Index</p> <p @click="loadPage('About')">About</p> <p @click="loadPage('Product')">Product</p> </div></template><script> export default{ }</script><style></style> 至此,全局混入大功告成,有心的讀者也可以試試局部混入(主要用于后期代碼維護)。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選