Vue之mixin全局的用法详解

个人觉得全局mixin就是给全部Vue文件添加一些公用的实例(方法,过滤器and so on)

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

ex:

step1: 先定义mixin.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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文件里面

1

2

import mixin from './mixin'

Vue.mixin(mixin)

全局混入是.mixin没有s

step3:在你的vue文件里面就可以使用mixin里面定义好的东西比如

1

2

3

4

5

6

7

8

data() {

  return {

   userName: "等你",

   time: this.formatDate(new Date()),

   arr: [1,2,3,4,5,'文字'],

   result: []

  }

 }

这个vue文件的数据源data里面的time就是引用混入进来的方法。

使用mixins里的方法

设置路由

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

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

?

1

<p @click="loadPage('Index')">Index</p>

Index页面如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

猜你喜欢

转载自blog.csdn.net/weixin_39939012/article/details/85095808