vue如何绑定全局的方法
Vue.prototype
方法挂载到 Vue.prototype 上面
缺点:绑定的东西多了会使vue实例过大,每次使用都要加上this
// 在项目入口的 main.js 里配置
import Vue from 'vue'
// 重置 message 防止重复点击重复弹出message弹框
import { message as Message } from "./resetMessage"
Vue.prototype.$message = Message
// 挂载之后,使用 this.$message 就可以调用
export default {
mounted() {
this.$message.success('操作成功')
}
}
使用Plugin Vue.use( plugin )
Vue.use的实现没有挂载的功能,只是触发了插件的install方法,本质还是使用了Vue.prototype。
缺点: 必须提供
install方法,绑定的东西多了会使vue实例过大
// plugin.js
import { message as Message } from "./resetMessage"
// install 是默认的方法。
// 当外界在 use 这个组件或函数的时候,就会调用本身的 install 方法,同时传一个 Vue 这个类的参数。
const install = Vue {
Vue.prototype.$message = Message
...
}
export default {
install
}
// 在项目入口 main.js 里配置
import Vue from 'vue'
import plugin from '@/plugin'
Vue.use(plugin);
// 在组件中使用
export default {
mounted() {
this.$message.success('操作成功')
}
}
利用全局混入Vue.mixin( mixin )
缺点:影响每一个之后创建的 Vue 实例
// mixin.js
export default {
data() {
},
methods: {
randomString(encode = 36, number = -8) {
return Math.random() // 生成随机数字, 0.123456
.toString(encode) // 转化成36进制, "0.4fzyo82mvyr"
.slice(number) // 截取为 "yo82mvyr"
}
}
}
// 在项目入口 main.js 里配置
import Vue from 'vue'
import mixin from '@/mixin'
Vue.mixin(mixin)
// 在组件中使用
export default {
mounted() {
this.randomString()
}
}
vue组件中写全局函数 vm.$on
在当前组件树的根 Vue 实例上注册全局方法vm-root
缺点:需要对每一个全局方法注册、销毁,调用也不方便
// 创建全局方法
this.$root.$on("fn", function () {
// ...
});
// 销毁全局方法
this.$root.$off("fn");
// 调用全局方法
this.$root.$emit("fn");
使用webpack.ProvidePlugin全局引入
- 首先在vue.config中引入webpack和path,然后在module.exports的configureWebpack对象中定义plugins,引入你需要的js文件;
- 其次如果你项目中有ESlint,还需要在根目录下的.eslintrc.js文件中,加入一个globals对象,把定义的全局函数类的属性名启用一下,不然会报错找不到该属性。
- 最后重启项目
缺点:项目需要重启
// vue.config.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, //开启代理
pathRewrite: {
'^/api': '/',
},
},
}
},
plugins: [
new webpack.ProvidePlugin({
UTILS: [path.resolve(__dirname, './src/utils/Utils.js'), 'default'], // 定义的全局函数类
TOAST: [path.resolve(__dirname, './src/utils/Toast.js'), 'default'], // 定义的全局Toast弹框方法
LOADING: [path.resolve(__dirname, './src/utils/Loading.js'), 'default'] // 定义的全局Loading方法
})
]
}
}
// .eslintrc.js
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的配置
}
// xxx.vue
computed: {
playCount() {
return (num) => {
// UTILS是定义的全局函数类
const count = UTILS.tranNumber(num, 0)
return count
}
}
}
最后一句
学习心得!若有不正,还望斧正。希望掘友们不要吝啬对我的建议。