溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Vue項(xiàng)目中使用全局mixin

發(fā)布時(shí)間:2021-01-12 15:09:15 來源:億速云 閱讀:217 作者:Leah 欄目:web開發(fā)

今天就跟大家聊聊有關(guān)如何在Vue項(xiàng)目中使用全局mixin,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

使用場(chǎng)景:貨幣單位,時(shí)間格式。這些如果在用到的頁面使用的話代碼會(huì)重復(fù)的很多,所以在全局混入這些實(shí)例會(huì)減少代碼量,可維護(hù)性也比較高。

ex:

step1: 先定義mixin.js

const mixin = {
 methods: {
  /**
   * 格式化時(shí)間
   * @param {string|number|object|Array} dateTime - 時(shí)間,可以是一個(gè)字符串、時(shí)間戳、表示時(shí)間的對(duì)象、Date對(duì)象或者******表示時(shí)間的數(shù)組
   * @param {string} [fmt] - 格式
   * @returns {string} 返回格式化后的日期時(shí)間,默認(rèn)格式: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: []
  }
 }

這個(gè)vue文件的數(shù)據(jù)源data里面的time就是引用混入進(jìn)來的方法。

使用mixins里的方法

設(shè)置路由

// 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)
  }
 ]
})

頁面調(diào)用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>

看完上述內(nèi)容,你們對(duì)如何在Vue項(xiàng)目中使用全局mixin有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI