Vue 3 reload component when variable changes
P粉090087228
P粉090087228 2023-12-27 20:06:22
0
1
504

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粉090087228
P粉090087228

reply all(1)
P粉344355715

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 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!