方法一:使用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>