当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue之mixin全局的用法详解

Vue之mixin全局的用法详解

2018年09月23日  | 移动技术网IT编程  | 我要评论

王扩桃,逃出绿房子,特卖淘宝

先贴上。

个人觉得全局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 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> 

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网