Creating a Vue 3 component that automatically refreshes when a variable is updated

I am attempting to reload the component when the 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 making an API call to retrieve the top scorers from the selected league.

I have attempted using :watch, v-on:, created()

Answer №1

<LeagueTopScorers /> will undergo re-rendering when there is a change in the selectedLeague, but it will not be remounted. It will only mount when the selectedLeague changes from a falsy value to a truthy one (as that's when the value of the v-if changes).

Your question has a few issues:

  • You are inquiring about a technical aspect, X, which you believe will address a business requirement, Y. This is known as an XY problem. Why not explain what exactly you want to achieve with Y? What output alteration do you seek based on what input modification?
  • The provided code snippet is insufficient to construct a functional example. Without clarity on what v-select is, or how <LeagueTopScorers /> operates, and the structure of the :is prop on <LeagueTopScorers />.

Based on the code excerpt you shared, here are my assumptions:

  • v-select appears to be either vue-select or Vuetify select component
  • You seem to expect :is to function similarly on <LeagueTopScorers /> as it does on <component />. Note: this might not be the case unless specifically implemented.
  • Finally, it seems like you aim to execute certain code within an initialization lifecycle hook of <LeagueTopScorers /> when replacing an object stored in selectedLeague with another object.

If my understanding is accurate, the most straightforward method to attain this behavior would be creating a computed property 2:

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

... and integrating it into v-if, :key, and :selectedLeague:

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

(excluding the <div v-if> wrapper).

The above approach will spawn a new instance of <LeagueTopScorers /> whenever leagueId changes, rendering only when leagueId is not falsy. This likely aligns with your intended technical objective 3.


Notes:
1 - for verification, utilize

onUpdated(() => console.log('updated...'))

2 - employ
selectedLeague.value?.id.toString()
if selectedLeague is a ref
3 - while I am confident the actual business requisites can be satisfied without generating a fresh instance of <LeagueTopScorers /> every time leagueId shifts, more details and context are necessary for further assistance

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the power of JavaScript, along with jQuery and other libraries, to access and manipulate content within an iframe that

Greetings to everyone. I am currently working on a project that involves an application with a view implemented using an iframe. The iframe's src is modified when the user interacts with certain elements in the "parent" document. Essentially, there i ...

TinyMCE - Utilizing selection.setContent along with getContent for the Warp Button

I am looking to implement a button that will wrap content with all tags. Snippet of Code: editor.addButton('MobileToggleArea', { text: '<M>', icon: false, onclick: function (){ editor.selection. ...

Sending an array of JSON data from PHP to JavaScript

After exploring various solutions on how to get JSON in JavaScript from a PHP array, I am still encountering an error. My myfile.php file includes: <?php ................ print json_encode($data, JSON_NUMERIC_CHECK); mysql_close($con); ?> <html&g ...

What are some effective ways to test asynchronous functions in React?

Looking for help to test async/Promise based methods in React components. Here is a simple example of a React component with async methods: import server from './server'; class Button extends Component { async handleClick() { if (await ca ...

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

Implementing pagination with complete page information using node.js and mongodb

Hello, I am currently working on implementing pagination in NodeJS and MongoDB. Check out the code I have written below: router.get("/PO_pagination", verify, async (req, res) => { console.log("req.query", req.query) try { let ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...

Steps for including a token in a Nuxt Axios instance

When trying to create an axios instance and add a token header, I encountered an error. const apiClient = axios.create({ baseURL: "...", }); apiClient.interceptors.request.use( (config) => { const token = localStorage.getItem("auth._toke ...

What is the best way to retrieve an accurately matched array?

I am working on a function that analyzes a string of DNA and should return an accurately matched DNA array. Here is the code snippet I have experimented with: function checkDNA(dna) { var dnaarr = []; for(var i = 0; i < dna.length; i++) { ...

Javascript inheritance concepts

Creating a set of classes in JavaScript to manage accounts presents a challenge for me. The main class is 'account', which serves as the parent class, while 'depositAccount' and 'savingsAccount' are its children. These classes ...

`replaceWith function limited to single use`

I'm encountering an issue where the replaceWith function is only working on the first instance. Even though I am getting updated data, it's not being written to the div after the initial replacement. $( "#searchboxform" ).keyup(function() { ...

Refresh a TextBox using an Ajax Response

Is there a way to dynamically update a textbox with the response from an ajax call? I've managed to get the response and assign it to the textbox using: document.getElementById("testPad").value = xmlHttpRequest.responseText; The issue is that the en ...

What are the steps to integrate a hijri datepicker in a Vue3 application?

In the process of creating a web app with vue3, I've encountered a challenge with finding a suitable hijri datepicker library that is compatible with vue3 and does not rely on jquery. I don't want to incorporate jquery into my app, so I'm on ...

Avoid duplicate items from being added to an array in AngularJS

I have created an Angular Single Page Application that includes a cart feature where users can add items. My goal is to prevent users from adding the same item to the cart more than once. function CartForm($scope) { $scope.products = [{ "descript ...

Is it possible to encounter mapActions error when Object.assign is not used?

x.vue file methods: { ...mapActions([ 'fetchTopicVideo', ]), } An error will occur, with the following details: ERROR in ./~/buble-loader!./~/vue-loader/lib/selector.js? type=script&index=0!./src/components/CardList.vue Modu ...

Error: AJAX responseText Mismatch detected

When I make an AJAX call in my code, everything seems to be working correctly. The PHP script responds with "success" when it should, and the response text is indeed "success". However, even though the output appears to be correct, the line if(returnVal == ...

Solving the image path issue in a Vue Component using webpack (inside Vuepress)

Incorporating the most recent Vuepress version (1.0.0-alpha.46), I have set up the documentation off the root directory with an assets folder for image storage. Referencing these images in markdown poses no issues. For example: ![ ](../assets/foobar.jpg) ...

Troubleshooting issues with debouncing a Redux dispatch and encountering unexpected results

I've been attempting to implement debounce for an API action that involves a dispatch call to a reducer. The goal is for the API call in the browser to debounce after a specific delay, but instead, it's resulting in multiple API calls after the d ...

Sequelize: Establishing multiple connections

Currently working with Sequelize in Node, I have two tables named User and Auth: User id name Auth: id token My goal is to establish relationships between these models. A User can possess multiple Auth entries, forming a to-many relati ...

Verifying user presence in Vue when making edits

Currently, I'm attempting to validate user existence in Vue using Vuetify inputs when trying to edit a User. The goal is to prevent an error if the username already exists, unless it is the old username of the user being edited without any changes mad ...