先贴上官方定义。
个人觉得全局mixin就是给全部Vue文件添加一些公用的实例(方法,过滤器and so on)
使用场景:货币单位,时间格式。这些如果在用到的页面使用的话代码会重复的很多,所以在全局混入这些实例会减少代码量,可维护性也比较高。
ex:
step1: 先定义mixin.js
const mixin = {
methods: {
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 mixin
step2:在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.js
import 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方法
Index
Index页面如下
// src/pages/Index这是index页面
Index
about
Product
至此,全局混入大功告成,有心的读者也可以试试局部混入(主要用于后期代码维护)。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



