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

使用vuex的時(shí)候,出現(xiàn)this.$store為undefined問(wèn)題

 更新時(shí)間:2023年06月27日 14:34:04   作者:yanguo110  
這篇文章主要介紹了使用vuex的時(shí)候,出現(xiàn)this.$store為undefined問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

使用vuex出現(xiàn)this.$store為undefined問(wèn)題

使用的場(chǎng)景

在open_show中調(diào)用update_info的時(shí)候出現(xiàn)undefined

解決的思路

剛開(kāi)始接觸vuex,碰到這個(gè)問(wèn)題,首先就是搜索一下,別人的一般都是this.$store.state為undefined,還是沒(méi)有什么思路,然后我看了一下項(xiàng)目中別人寫(xiě)的代碼中就可以調(diào)用,再看下目錄,難道和目錄有關(guān),試了一下,并沒(méi)有什么作用,就換種思路,打印了一下this,發(fā)現(xiàn)this的指向出現(xiàn)問(wèn)題。

this指向的解決方法

第一種:

methods: {
      update_info:function(self,data){
        alert(self.$store);
        self.$store.commit("info",data);
      },
      open_show: function () {
	     var self =this;
       this.update_info(self,this.flag);
       }
   }

第二種:

var self =this;
  export default {
	  methods: {
	      update_info:function(data){
	        alert(self.$store);
	        self.$store.commit("info",data);
	      },
	      open_show: function () {
	       this.update_info(this.flag);
	       }
       },
     created(){
		  self = this;
  }
}

當(dāng)然以上的方法是解決特定場(chǎng)景下的this指向問(wèn)題,即方法調(diào)用方法時(shí),如果方法很多地方都調(diào)用的話,推薦使用第二種,第一種當(dāng)方法公用時(shí)還需要修改,如果只是是單個(gè)調(diào)用,方法一推薦使用。

vuex使用token時(shí)$store一直undefined

報(bào)錯(cuò):Cannot read properties of undefined(reading '$store') at eval

先直接說(shuō)解決方法,后面再一一分析。

解決方法

將then()中的普通函數(shù)換成箭頭函數(shù),即可解決錯(cuò)誤,該錯(cuò)誤產(chǎn)生的原因其實(shí)是this的指向問(wèn)題。

錯(cuò)誤代碼展示:

分析原因

首先在main.js中對(duì)$store進(jìn)行打印,觀察是否真的將store注冊(cè)到Vue實(shí)例中

打印結(jié)果:

控制臺(tái)能對(duì)$store進(jìn)行打印,說(shuō)明store是存在于vue中的,所以排除vuex安裝錯(cuò)誤和store沒(méi)有注冊(cè)到實(shí)例例中的錯(cuò)誤。

再觀察方法中如何調(diào)用store——直接使用this.$store,那么會(huì)不會(huì)是因?yàn)檫@里的this并不指向vue呢,經(jīng)過(guò)上網(wǎng)查證,我在vue文檔中得到了這么一句話:

All lifecycle hooks are called with their 'this' context pointing to the Vue instance invoking it.

就是說(shuō),在Vue所有的生命周期鉤子方法(如created,mounted, updated以及destroyed)里使用this,this指向調(diào)用它的Vue實(shí)例,即(new Vue)。

因?yàn)樵趖hen()中使用了普通函數(shù),而普通函數(shù)中的this不指向vue,自然無(wú)法找到vue.$store,

將普通函數(shù)換成箭頭函數(shù)之后,箭頭函數(shù)沒(méi)有自己的this, 它的this是繼承而來(lái),所以箭頭函數(shù)內(nèi)的this指向new Vue,也就是我定義的myVue,就可以使用this.$store了。

解決方法示例

總結(jié)

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

相關(guān)文章

最新評(píng)論