在不同的組件頁(yè)面用到同樣的方法,比如格式化時(shí)間,文件下載,對(duì)象深拷貝,返回?cái)?shù)據(jù)類型,復(fù)制文本等等。這時(shí)候我們就需要把常用函數(shù)抽離出來(lái),提供給全局使用。那如何才能定義一個(gè)工具函數(shù)類,讓我們?cè)谌汁h(huán)境中都可以使用
第一種
- 直接添加到Vue實(shí)例原型上(缺點(diǎn)就是綁定的東西多了會(huì)使vue實(shí)例過(guò)大)
//main.js 里面
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import utils from './utils/Utils'
Vue.prototype.$utils = utils
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
//組件中使用
methods: {
fn() {
let time = this.$utils.formatTime(new Date())
}
}
第二種方式
- 使用webpack.ProvidePlugin全局引入
首先在vue.config中引入webpack和path,然后在module.exports的configureWebpack對(duì)象中定義plugins,引入你需要的js文件
const baseURL = process.env.VUE_APP_BASE_URL
const webpack = require('webpack')
const path = require("path")
module.exports = {
publicPath: './',
outputDir: process.env.VUE_APP_BASE_OUTPUTDIR,
assetsDir: 'assets',
lintOnSave: true,
productionSourceMap: false,
configureWebpack: {
devServer: {
open: false,
overlay: {
warning: true,
errors: true,
},
host: 'localhost',
port: '9000',
hotOnly: false,
proxy: {
'/api': {
target: baseURL,
secure: false,
changeOrigin: true, //開(kāi)啟代理
pathRewrite: {
'^/api': '/',
},
},
}
},
plugins: [
new webpack.ProvidePlugin({
UTILS: [path.resolve(__dirname, './src/utils/Utils.js'), 'default'], // 定義的全局函數(shù)類
TOAST: [path.resolve(__dirname, './src/utils/Toast.js'), 'default'], // 定義的全局Toast彈框方法
LOADING: [path.resolve(__dirname, './src/utils/Loading.js'), 'default'] // 定義的全局Loading方法
})
]
}
}
這樣定義好了之后,如果你項(xiàng)目中有ESlint,還需要在根目錄下的.eslintrc.js文件中,加入一個(gè)globals對(duì)象,把定義的全局函數(shù)類的屬性名啟用一下,不然會(huì)報(bào)錯(cuò)找不到該屬性。
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint',
sourceType: 'module'
},
env: {
browser: true,
node: true,
es6: true,
},
"globals":{
"UTILS": true,
"TOAST": true,
"LOADING": true
}
// ...省略N行ESlint的配置
}
組件中使用
computed: {
playCount() {
return (num) => {
// UTILS是定義的全局函數(shù)類
const count = UTILS.tranNumber(num, 0)
return count
}
}
}
//本文出自http://www.itdecent.cn/p/a1e08d3c990c