如何在Vue项目中使用全局mixin

今天就跟大家聊聊有关如何在Vue项目中使用全局mixin,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

使用场景:货币单位,时间格式。这些如果在用到的页面使用的话代码会重复的很多,所以在全局混入这些实例会减少代码量,可维护性也比较高。

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 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方法

<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>

看完上述内容,你们对如何在Vue项目中使用全局mixin有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。