方法一:使用Vue.prototype
//在mian.js中写入函数
Vue.prototype.getToken = function (){
...
}
//在所有组件里可调用函数
this.getToken();
方法二:使用exports.install+Vue.prototype
// 写好自己需要的fun.js文件
exports.install = function (Vue, options) {
Vue.prototype.getToken = function (){
...
};
};
// main.js 引入并使用
import fun from './fun' Vue.use(fun);
//在所有组件里可调用函数
this.getToken();
在用了exports.install方法时,运行报错exports is not defined
解决方法:
export default {
install(Vue) {
Vue.prototype.getToken = {
...
}
}
}
方法三:使用全局变量模块文件
Global.vue文件:
<script>
const token='12345678';
export default {
methods: {
getToken(){
....
}
}
}
</script>
在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。
<script>
import global from '../../components/Global'//引用模块进来
export default {
data () {
return {
token:global.token
}
},
created: function() {
global.getToken();
}
}
</script>
- THE END -
最后修改:2022年7月15日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://www.95app.top/vue%e5%85%a8%e5%b1%80%e6%96%b9%e6%b3%95/