溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue中的Vue.prototype如何用

發(fā)布時(shí)間:2022-04-28 16:36:01 來(lái)源:億速云 閱讀:380 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹了Vue中的Vue.prototype如何用的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Vue中的Vue.prototype如何用文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

1. 基本示例

在main.js中添加一個(gè)變量到 Vue.prototype

Vue.prototype.$appName = 'My App'

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

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

控制臺(tái)會(huì)打印出 My App,就這么簡(jiǎn)單!

2. 為實(shí)例prototype設(shè)置作用域

為什么 appName 要以 開(kāi)頭?這很重要嗎?這里沒(méi)有什么魔法。 開(kāi)頭? 這很重要嗎? 這里沒(méi)有什么魔法。開(kāi)頭?這很重要嗎?這里沒(méi)有什么魔法。 是在 Vue 所有實(shí)例中都可用的 property 的一個(gè)簡(jiǎn)單約定。這樣做會(huì)避免和已被定義的數(shù)據(jù)、方法、計(jì)算屬性產(chǎn)生沖突。
如果我們?cè)O(shè)置:

Vue.prototype.appName = 'My App'

那么如下的代碼輸出什么:

new Vue({
  data: {
    // 啊哦,`appName` 也是一個(gè)我們定義的實(shí)例 property 名!
    appName: 'The name of some other app'
  },
  beforeCreate: function () {
    console.log(this.appName)
  },
  created: function () {
    console.log(this.appName)
  }
})

日志中會(huì)先出現(xiàn) "My App",然后出現(xiàn) "The name of some other app",因?yàn)?this.appName 在實(shí)例被創(chuàng)建之后被 data 覆寫(xiě)了。我們通過(guò) 為實(shí)例property設(shè)置作用域來(lái)避免這種事情發(fā)生。你還可以根據(jù)你的喜好使用自己的約定,諸如為實(shí)例 property 設(shè)置作用域來(lái)避免這種事情發(fā)生。 你還可以根據(jù)你的喜好使用自己的約定,諸如為實(shí)例property設(shè)置作用域來(lái)避免這種事情發(fā)生。你還可以根據(jù)你的喜好使用自己的約定,諸如_appName 或 ΩappName,來(lái)避免和插件或未來(lái)的插件相沖突。

3. 注冊(cè)和使用全局變量

每個(gè)組件都是一個(gè)vue實(shí)例,Vue.prototype加一個(gè)變量,只是給每個(gè)組件加了一個(gè)屬性,這個(gè)屬性的值并不具有全局性。
比如以下例子:

// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false
Vue.prototype.$appName = 'main'

new Vue({
    el: '#app',
    store,
    router,
    components: { App },
    template: '<App/>',
})

// 給所有組件注冊(cè)了一個(gè)屬性 $appName,賦予初始值 'main' ,所有組件都可以用 this.$appName 訪問(wèn)此變量;
// 如果組件中沒(méi)有賦值,初始值都是'main'
// home.vue
<template>
  <div>
    <div @click="changeName">change name</div>
    <div @click="gotoTest2">goto test2</div>
  </div>
</template>

<script>
export default {
  methods:{
    changeName(){
      this.$appName = "test1"
    },
    gotoTest2(){
      this.$router.push('/about')
    } 
  }
}
</script>
// about.vue
<template>
  <div>
    <div>{{this.$appName}} in test2</div>
  </div>
</template>

點(diǎn)擊 home 中的 change name 再跳轉(zhuǎn)about,about里面還是顯示 main in test2
如果要實(shí)現(xiàn)全局變量的功能,需要把屬性變?yōu)橐妙愋?br/>

Vue.prototype.$appName = { name: 'main' }

后面使用 this.$appName.name 改變和引用相應(yīng)的值
這進(jìn)入 about 后顯示 test1 in test2

4. 原型方法的上下文

在 JavaScript 中一個(gè)原型的方法會(huì)獲得該實(shí)例的上下文,也就是說(shuō)可以使用 this 訪問(wèn):數(shù)據(jù)、計(jì)算屬性、方法或其它任何定義在實(shí)例上的東西。
讓我們將其用在一個(gè)名為 $reverseText 的方法上:

 // main.js
Vue.prototype.$reverseText = function (propertyName) {
  this[propertyName] = this[propertyName]
    .split('')
    .reverse()
    .join('')
}
// 相應(yīng)組件
<script>
export default {
  data() {
    return{
      message: 'Hello'
    }
  },
  created() {
    console.log(this.message) // => "Hello"
    this.$reverseText('message')
    console.log(this.message) // => "olleH"
  }
}
</script>

5. 應(yīng)用示例

5.1 引入 axios

npm install vue-axios --save

npm install qs.js --save  //它的作用是能把json格式的直接轉(zhuǎn)成data所需的格式
// mian.js
import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

Vue.prototype.$axios = axios    //全局注冊(cè),使用方法為:this.$axios
Vue.prototype.qs = qs           //全局注冊(cè),使用方法為:this.qs

// 相應(yīng)組件
<script>
  export default{
    data(){
      return{
        userId:666,         
        token:'',
      }
    },
    created(){
      this.$axios({
        method:'post',
        url:'api',
        data:this.qs.stringify({    //這里是發(fā)送給后臺(tái)的數(shù)據(jù)
          userId:this.userId,
          token:this.token,
        })
      }).then((response) =>{          //這里使用了ES6的語(yǔ)法
        console.log(response)       //請(qǐng)求成功返回的數(shù)據(jù)
      }).catch((error) =>{
        console.log(error)       //請(qǐng)求失敗返回的數(shù)據(jù)
      })
    }
  }
</script>

Vue.prototype、Vue.component和Vue.use區(qū)別

1、Vue.prototype

在多個(gè)地方都需要使用但不想污染全局作用域的情況下,這樣定義,在每個(gè) Vue 實(shí)例中都可用。
參考:https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html
$ 表示這是一個(gè)在 Vue 所有實(shí)例中都可用的屬性
常用于方法、變量等

import echarts from 'echarts'
Vue.prototype.$echarts = echarts

2、vue.component

全局注冊(cè)組件,
第一個(gè)參數(shù)是調(diào)用組件時(shí)寫(xiě)的組件名
第二個(gè)參數(shù)是引入組件時(shí)寫(xiě)的名稱
可用于注冊(cè)自定義組件

import myLoading from 'base/loading'
Vue.component('myLoading',myLoading);

3、Vue.use

同樣是全局注冊(cè),和component的區(qū)別是接收的參數(shù)必須有install方法
常用于注冊(cè)第三方插件

import ElementUI from 'element-ui';
Vue.use(ElementUI);

關(guān)于“Vue中的Vue.prototype如何用”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Vue中的Vue.prototype如何用”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI