Vue之mixin全局的用法详解

先贴上官方定义

个人觉得全局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 } */ 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:'https://www.jb51.net/', 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>

至此,全局混入大功告成,有心的读者也可以试试局部混入(主要用于后期代码维护)。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6d47cda7d79cc1e5e3d177e03229d9ea.html