Troubleshooting: Why is Vue's v-if directive not updating after using on

I'm facing an issue where I want a div to only appear once a specific variable changes from false to true. I have tried changing the value of the variable once the component is mounted, but the v-if directive does not seem to work as expected in displaying the div.

<script setup>
  import { onMounted } from 'vue'

  let onceMounted = false
  
  onMounted(() => {
    onceMounted = true
    console.log(onceMounted)
  });
<div>
  Hello
  <div v-if="onceMounted === true">
    World
  </div>
</div>

Although the console log shows that the variable changes correctly, the v-if directive does not update the div. I have even tried using v-show after researching similar issues like this one. Is there something essential that I might be overlooking?

Answer №1

enableReactive should be made reactive using a reference, then utilize .value to modify it:

<script setup>
  import { onMounted, ref } from 'vue'

  const enableReactive = ref(false)
  
  onMounted(() => {
    enableReactive.value = true
    console.log(enableReactive.value)
  });
</script>
<div>
  Hello
  <div v-if="enableReactive"><!-- no need for .value in the template -->
    World
  </div>
</div>

Answer №2

Don't overlook the need to assign a value of true to the onceMounted variable;

Previous Code:

onMounted(() => {
    onceMounted = false
    console.log(onceMounted)
  });

Updated Code:

onMounted(() => {
    onceMounted = true
    console.log(onceMounted)
  });

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

Guide on Generating Dynamic JSON to Set and Retrieve Values for Forms and Displaying the Bound Values

I'm a beginner in Ionic 3 and I'm having trouble creating a page that redirects to another page without validation. I want to display the data on the new page, but it's not working. Please help! I also want to create a dynamic JSON object a ...

"Using Three.js GLTF, switch the material of one object to match the material of

Recently, I encountered an interesting challenge with a scene imported from a glb-file using GLTFLoader. The scene features various objects of guys in different colors, each with its own material (RedMat, BlueMat, GreenMat, etc) created in Blender. Interes ...

On startup of the chrome app, read and load a JSON file into a variable

As I develop a chrome app, my goal is to store all configuration defaults in json file(s) alongside other assets. I am currently using AJAX requests to load them, but I'm wondering if there is a more efficient way to handle this. Is there perhaps an o ...

Nuxt - asyncData ISSUE: "Variable '$axios' is inferred to have an 'any' type."

Referencing the guidelines provided at Encountering an error logged in console while executing yarn dev: ERROR ERROR in pages/index.vue:51:21 ...

Having trouble updating the ASP Dropdown that has list items added through a jQuery AJAX call? Keep receiving the error message "Invalid postback or callback"?

I encountered a simple problem that I ended up complicating. In my web application, I have an ASP Dropdown that I want to populate with values from the database. To achieve this, I used jquery and Ajax to dynamically add list items to the dropdown successf ...

I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page. index.vue head: { bodyAttrs: { id: 'overview' }, script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min ...

Attempting to store a specific h1 text.event as a variable, allowing it to be saved upon input of the initial letter

After typing the second key, you can continue to input more characters as desired. It is possible to customize the text displayed in the h1 using your own name or any other text of your preference without needing a textbox. $(document).keypress(functio ...

What is the best method for selecting or isolating the code for a single animation created using JavaScript?

Currently, I am attempting to extract the CSS and JS code of an image reveal animation that is part of a static HTML page: https://i.stack.imgur.com/bnmaO.gif The challenge lies in the fact that the desired effect is one among many showcased image animat ...

POST request returned a null response in the xhr.responseText

Check out the structure of my JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://myajaxurl.com/lyric", true); var data = "lyric"; xhr.onreadystatechange = function() { if (xhr.readyState == 4) { console.log(xhr.responseText); ...

What is the best way to sort a table by column index using HTML?

I find myself in a situation where I am not well-versed in HTML, Javascript, and CSS. Here is the scenario: <div class="table"> <table class="display-table"> <thead> <tr> ...

Ensuring that Bootstrap rows fill the entire height within a column

While working on a template with nested rows and columns in Bootstrap, the layout ended up looking like this: <div class="col-5"> <div class="row"> <div class="col-3 border border-secondary">Truck Number</div> ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Characters that have been escaped are showing up when adding them to an HTML element

Through an AJAX call, I am fetching HTML code and appending it to an existing HTML element. However, the appended code includes escaped characters, leading to broken HTML with elements appearing scattered like this: Contact Us ▸<\/a><\ ...

What is the best way to update React State after making an asynchronous call to MongoDB?

I have been facing a common issue, but couldn't find an up-to-date solution on Stack Overflow specifically for React/Meteor. My goal is to query a mongoDB to retrieve data and then pass it into the state of my React components. Currently, I am queryin ...

The "variable" used in the React app is not defined, resulting in a no

Following the tutorial of Mosh Hamedani, I attempted to create a react-app. You can watch the tutorial here. I followed his instructions exactly as mentioned. I encountered an issue when trying to pass an argument named product to a function called on on ...

What is the best way to display an image in HTML?

I have successfully created an autocomplete search box that retrieves product names, but I am struggling to display the product photos. Here is the code snippet I am using: <asp:TextBox ID="txtContactsSearch" runat="server" Width="261"></asp:Text ...

Encountering problem animating rotation of a .glb model post gltfjsx conversion

I recently utilized a gltf to jsx converter available on GitHub (https://github.com/pmndrs/gltfjsx) in order to generate JSX components for my model. Despite this, I am encountering difficulties in figuring out how to modify my model.js so that the model s ...

What is the best way to combine JSON objects from a two-dimensional array into a single array using JavaScript?

I have a JSON object within an array that I want to push to an employeeArray. employeeArray =[ [ { "ID":"967", "NAME":"Dang, Lance D", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e426f6 ...

Generate a customized form based on selected radio button option

Hey there! I'm curious to know if it's achievable to utilize Javascript/jQuery or Ajax in displaying a form depending on a radio button selection. Here's the scenario: I have two unique forms. If one radio button is chosen, I'd like to ...