从 Vue.js 中获取的源中获取对象的真实值

我通过从外部 API 中获取数据来获取国家/地区列表VueX。然后我使用突变将这些国家列表存储到一个州。


所以实际上,我将国家存储在一个变量中,我this.$state.getters.countryList从一个组件中引用它。现在我需要比较该列表中是否存在变量。


所以我用这个方法: this.$store.getters.countryList.indexOf('usa').


'usa'我知道该列表中存在一个事实,但我总是得到-1结果。


然后我尝试this.$state.getters.countryList通过 using调试值,并在控制台中console.log(this.$state.getters.countryList)得到[__ob__: Observer]结果。


这就是我想要做的:


  mounted() {

    if (this.$store.getters.countryList.indexOf('usa')) {

       //Do something

      }

  }

如何获得实际值this.$state.getters.countryList并将其与执行检查一起使用indexOf()以执行其他操作?


拉丁的传说
浏览 123回答 1
1回答

慕娘9325324

由于从外部 API 获取数据是一项async操作,因此您尝试访问的数据在您需要时可能不可用,正如 @Phil 所述。fetch出于这个原因,您可以设置一个观察者在操作完成并countryList加载后运行您的指令集:在store.js中,假设您的商店最初countryList设置为:nullexport const state = () => ({ countryList: null})然后在你的mounted()钩子中你会设置一个观察者:mounted() { this.$store.watch(  state => state.countryList,  (value) => {   if (value) {      //instruction once countryList is loaded    }  } )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript