【问题标题】:Call API automatically to fetch data with prop value when component is displayed in Vue.jsVue.js 中显示组件时,自动调用 API 获取带有 prop 值的数据
【发布时间】:2020-05-05 13:10:27
【问题描述】:

我有一个显示共同基金列表的页面。对于每个共同基金,我都有一个按钮来显示他们的资产净值历史。此按钮调用具有嵌入式 API 调用的组件以获取 NAV 历史记录。我将要为其获取数据的基金代码作为道具传递给组件。但是,当调用 prop 时,我无法自动触发 API 调用。

这是我现在的代码:

父组件(主页面):

<template>
   <!-- some code -->
      <a href="#" @click="fetchNavHistory(fund)">
          <v-icon small>history</v-icon>
      </a>
   <!-- some more code -->

   <NAVHistory 
      :show="showNavHistory"
      :amfi_code="amfi_code"
      ref="history"
      @hide="showNavHistory=false"
   />

</template>

export default {
  name: "FundList",
  components: {
      NAVHistory
  },
  data() {
    return {
      showNavHistory: false,
      amfi_code: 0
    }
  },
  methods:{
   fetchNavHistory(fund){
      this.amfi_code = fund.amfi_code
      this.showNavHistory = true
      var child = this.$refs.history
      child.fetchNavHistory()
    }
  }
}

子组件(显示 NAV 历史的地方):

<template>
    <!-- some code -->
</template>

<script>
export default {
    props: {
        show: Boolean,
        amfi_code: Number
    },
    data(){
        return{
            apiURL: process.env.VUE_APP_BASEURL,
            navHistory: [],
        }
    },
    methods: {
        async fetchNavHistory(){
            try{
              const response = await fetch(this.apiURL + '/navhistory', {
                method: 'POST',
                body: JSON.stringify({"amfi_code": this.amfi_code}),
                headers: {'content-type': 'application/json; charset=UTF-8'},
            })
              const data = await response.json()
              console.log(data)
              this.navHistory = data
            } catch(error){
              console.log(error)
            }
        }
    }
}
</script>

起初我尝试在updated() 事件上调用fetchNavHistory() 方法。但是当组件显示在屏幕上时,它会不停地调用 API。

然后我尝试为 show 属性添加 watch。但这根本不起作用。

最后,作为一种解决方法,我从父组件本身调用 API。当它工作时,它使用 amfi_code 的先前值调用组件,而不是更新的值。所以第一次调用时,amfi_code 被作为 0 传递。

有没有办法在组件显示时安全触发 API 调用,即 show 属性设置为 true?

【问题讨论】:

  • 您可以使用deep:true 选项来监视手表,这样在安装组件时将触发手表。或者您可以在 mounted 钩子上调用 API 并检查其中的 show 属性
  • deep:true 是我所需要的。否则手表不会触发呼叫。这到底是做什么的?我还必须添加 immediate:true 否则它不会在道具刚初始化时第一次触发。如果您将其写为答案,我可以将其标记为已接受的答案。

标签: vue.js


【解决方案1】:

您可以尝试使用 deep:true 选项进行监视,这样在挂载组件时将触发监视。或者您可以在挂载的钩子上调用 API 并检查其中的 show prop。

deep:true 表示手表会查看是否不仅对被监视的道具发生了变化,而且对所有嵌套的道具也发生了变化。

immediate:true 表示在安装组件后会触发 watch(当被监视的 prop 具有初始值时)。

【讨论】:

  • 感谢您的解释。即使我已经弄清楚要做什么,我还是不明白深层和直接参数在做什么。现在很清楚了。
猜你喜欢
  • 2021-02-14
  • 1970-01-01
  • 2017-04-20
  • 2019-02-06
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
相关资源
最近更新 更多