我們一般的做法是在 src 檔案夾下 建立一個 util 檔案夾,util 檔案夾裡面存放一個 utils.js 檔案,這個 js 檔案中存放公共的函數。下面講解大概三種用法。
一、對 utils.js 通過 export default 預設導出為對象
utils.js 内容:
//import {Message, MessageBox} from 'element-ui' // elementui 引入(這裡根據個人需求決定是否需要導入)
export default {
//等同于test: function ()...
test(x){
console.log(x)
},
hello(){
console.log("Hello World!")
}
}
在main.js中引入:
//公共js函數
import utils from "@/util/utils"; // @ 預設的是 src 檔案夾,後面省略了utils.js 後面的字尾名js
Vue.prototype.$utils = utils; //直接定義在vue的原型上面
this.$utils.hello( )
二、對 utils 通過 export 預設導出
utils.js 内容:
function test(x){
console.log(x)
}
function hello(){
console.log("Hello World!")
}
export default{ //注意這裡是default
test,
hello
}
在元件中就可以通過 import utils from '@/util/utils.js' 引入,用法為: utils.hello( )
三、對 utils.js 通過 export 普通導出
utils.js 内容:
export function test(x){
console.log(x)
}
export function hello(){
console.log("Hello World!")
}
然後在元件中通過 import { test, hello } from '@/util/utils.js' 引入(這裡可以根據自己的需求,用到哪些函數,就引入哪些函數),用法為 test( )