欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue實(shí)現(xiàn)定義一個(gè)全局實(shí)例Vue.prototype

 更新時(shí)間:2023年07月03日 09:40:42   作者:web前端 zxp  
這篇文章主要介紹了vue實(shí)現(xiàn)定義一個(gè)全局實(shí)例Vue.prototype,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

vue定義一個(gè)全局實(shí)例Vue.prototype

定義與使用

定義:

Vue.prototype.$appName = 'My App'

使用:

this.$appName (任何地方)

使用場景

你可能會(huì)在很多組件里用到數(shù)據(jù)/實(shí)用工具,但是不想污染全局作用域。

這種情況下,你可以通過在原型上定義它們使其在每個(gè) Vue 的實(shí)例中可用

Vue.prototype.$appName = 'My App'

這樣 $appName 就在所有的 Vue 實(shí)例中可用了,甚至在實(shí)例被創(chuàng)建之前就可以。

如果我們運(yùn)行:

new Vue({
  beforeCreate: function () {
    console.log(this.$appName)
  }
})

則控制臺(tái)會(huì)打印出 My App。就這么簡單!

為什么appName要以$開頭?這很重要嗎?它會(huì)怎樣?

$ 是在 Vue 所有實(shí)例中都可用的 property 的一個(gè)簡單約定。

這樣做會(huì)避免和已被定義的數(shù)據(jù)、方法、計(jì)算屬性產(chǎn)生沖突。

vue定義全局方法的三種實(shí)現(xiàn)

方法一:使用Vue.prototype

//在mian.js中寫入函數(shù)
Vue.prototype.getToken = function (){
? ...
}
//在所有組件里可調(diào)用函數(shù)
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);
//在所有組件里可調(diào)用函數(shù)
this.getToken();

在用了exports.install方法時(shí),運(yùn)行報(bào)錯(cuò)exports is not defined

解決方法:

export default {
? ? install(Vue) ?{
? ? ? ? Vue.prototype.getToken = {
? ? ? ? ? ?...
? ? ? ? }
? ? }
}

方法三:使用全局變量模塊文件

Global.vue文件:

<script>
? ? const token='12345678';
? ? export default {
? ? ? ? methods: {
? ? ? ? ? ? getToken(){
? ? ? ? ? ? ? ? ....
? ? ? ? ? ? }
? ? ? ? }
? ? }
</script>

在需要的地方引用進(jìn)全局變量模塊文件,然后通過文件里面的變量名字獲取全局變量參數(shù)值。

<script>
import global from '../../components/Global'//引用模塊進(jìn)來
export default {
? ? data () {
? ? ? ? return {
? ? ? ? ? ? token:global.token
? ? ? ? }
? ? },
? ? created: function() {
? ? ? ? global.getToken();
? ? }
}
</script>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論