search

Home  >  Q&A  >  body text

Vue 3 reload component when variable changes

I'm trying to reassign the component if selectedLeague has changed

<label class="label">Select league</label>
<div class="selector">
  <v-select
      v-model="selectedLeague"
      :dropdown-should-open="dropdownShouldOpen"
      :options="leagues"
      label="displayLeague"
      placeholder="Select a league"
  />
</div>

<div v-if="selectedLeague">
  <LeagueTopScorers :is="selectedLeague" :selectedLeague="selectedLeague.id.toString()" />
</div>

In the LeagueTopScorers component I am getting the API to get the top scorers in the selected league.

I tried: watch, v-on:, created()

P粉090087228P粉090087228343 days ago528

reply all(1)I'll reply

  • P粉344355715

    P粉3443557152023-12-28 15:00:30

    IndeedRe-render when selectedLeague changes1 , but it won't reinstall. It will only be mounted if selectedLeague changes from the falsy value to the truthy value (because that's when v-if< /code> changes).

    There are some problems with your question:

    • You're asking about a technical aspect (let's call it X) that you think will solve a business need (let's call it Y). This is a classic XY problem. Why don't you describe Y's requirements? (eg: what you want to achieve). What changes in output would you like to see when the input changes?
    • The code you posted is insufficient to create a runnable example. We don't know what v-select is, what is, or what the :is attribute is in .

    Based on the code snippet you posted, I'm guessing the following:

    • v-select is vue-select or Vuetify select component
    • You expect :is to work the same way on as it does on . Tip: No, unless you code it yourself, which I doubt
    • Last but not least, I think you want to put some code into the init lifecycle hook of (for example: onMounted) in your Replaces the object stored in selectedLeague with another object.

    If I'm correct, the simplest and cleanest way to achieve this behavior is to create a calculation 2:

    const leagueId = computed(() => selectedLeague?.id.toString() || '')
    

    ...and use it in v-if, :key and :selectedLeague:

    <LeagueTopScorers
      v-if="leagueId"
      :selectedLeague="leagueId"
      :key="leagueId" />
    

    (without

    wrapper).

    Every time leagueId changes, the above creates a new instance of and only renders one if leagueId is not false. I believe this is what you are technically trying to achieve3.


    Comments:
    1 - To verify, use onUpdated(() => console.log('updated...'))
    2 - Use selectedLeague.value?.id.toString() if selectedLeague is a ref
    3 - Also, I'm sure there's no need to create the every time the leagueId changes, but if not I can't be of more help with more details and/or context

    reply
    0
  • Cancelreply