当前位置:Gxlcms > JavaScript > Vue之mixin全局的用法详解

Vue之mixin全局的用法详解

时间:2021-07-01 10:21:17 帮助过:33人阅读

先贴上官方定义。

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

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

ex:

step1: 先定义mixin.js

  1. const mixin = {
  2. methods: {
  3. /**
  4. * 格式化时间
  5. * @param {string|number|object|Array} dateTime - 时间,可以是一个字符串、时间戳、表示时间的对象、Date对象或者******表示时间的数组
  6. * @param {string} [fmt] - 格式
  7. * @returns {string} 返回格式化后的日期时间,默认格式:2018年1月11日 15:00
  8. * @see [momentjs]{@tutorial http://momentjs.cn/}
  9. */
  10. formatDate (dateTime, fmt = 'YYYY年M月DD日 HH:mm:ss') {
  11. if (!dateTime) {
  12. return ''
  13. }
  14. moment.locale('zh-CN')
  15. dateTime = moment(dateTime).format(fmt)
  16. return dateTime
  17. }
  18. }
  19. }export defaullt mixin

step2:在main.js文件里面

  1. import mixin from './mixin'
  2. Vue.mixin(mixin)

全局混入是.mixin没有s

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

 

  1. data() {
  2. return {
  3. userName: "等你",
  4. time: this.formatDate(new Date()),
  5. arr: [1,2,3,4,5,'文字'],
  6. result: []
  7. }
  8. }

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

使用mixins里的方法

设置路由

  1. // src/router/index.js
  2. import Vue from 'vue'
  3. import Router from 'vue-router'
  4. Vue.use(Router)
  5. export default new Router({
  6. mode:'history',
  7. routes: [
  8. {
  9. path:'/',
  10. redirect:'/index'
  11. },
  12. {
  13. path: '/about',
  14. name: 'About',
  15. component:resolve => require(['@/pages/About'],resolve)
  16. },
  17. {
  18. path: '/index',
  19. name: 'Index',
  20. component:resolve => require(['@/pages/Index'],resolve)
  21. },
  22. {
  23. path: '/product',
  24. name: 'Product',
  25. component:resolve => require(['@/pages/Product'],resolve)
  26. }
  27. ]
  28. })

页面调用mixins里的loadPage方法

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

Index页面如下

  1. // src/pages/Index
  2. <template>
  3. <div>
  4. <p>这是index页面</p>
  5. <p @click="loadPage('Index')">Index</p>
  6. <p @click="loadPage('About')">About</p>
  7. <p @click="loadPage('Product')">Product</p>
  8. </div>
  9. </template>
  10. <script>
  11. export default{
  12. }
  13. </script>
  14. <style>
  15. </style>

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

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

人气教程排行