Build a brand new root component in Vue JS

I am facing a challenge with destroying and re-creating the root application component. Below is my template structure:

<div id="app">
  {{ num }}
</div>

Here is the code I have implemented:

 if (app) {
      app.$destroy();
    } else {
      app = new Vue(Object.assign({
        el: '#app',
      }, { data: { num: Math.random() } }))
    }

When this code runs on button click, it fails to properly clean the template and refresh the data being passed. Can you help me understand why this might be happening?

Answer №1

It seems like you may be trying to approach a problem in a manner that is not recommended or possibly misusing Vue.

Regarding your issue, the code snippet you provided:

if (app) {
  app.$destroy();
}

According to the documentation:

Completely destroy a vm. Clean up its connections with other existing vms, unbind all its directives, turn off all event listeners.

The documentation does not mention that the element to which the Vue app is attached will change automatically. If you want to clean up the DOM, you need to remove the content manually.

After executing app.$destroy(), the variable app will still hold the destroyed Vue instance (it won't be unset magically). Subsequent executions of the code will not trigger the else block. You also need to set app to something that evaluates as falsy.

if (app) {
  app.$destroy();
  app = undefined;
}

Now that app is set to undefined, the next time the if statement is evaluated, the else block will be executed and a new instance will be created.

Answer №2

The scenario you mentioned is quite general and lacks specific details, however, it seems like you're looking to manually update something that isn't refreshing automatically.

In order to refresh your component, you can utilize

this.$forceUpdate()

to trigger a forced reload of the component.

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

Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents ...

Ways to alter and remove ArrayList arrangement

I am new, so please excuse all the questions. Could you kindly explain to me? <ul id="example-1"> <li v-for="item in items"> {{ item.message }} <v-btn>up</v-btn> <v-btn>down</v-btn> ...

Ways to create a clickable anchor tag without using any text

I am currently designing my own website and incorporating links to various social media platforms using icons. However, I am facing an issue where the links are not clickable. For a detailed look at my problem, you can refer to this JSFiddle: http://jsfid ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Guide to using Vue.js and Vue Router to create a sub menu for the children of the current route

I am currently working on customizing the navigation for my Vue application. My goal is to create a main menu at the top that displays all the root level routes, and a side menu that appears when navigating through child routes. Here is an example of what ...

the specified computed property does not have a value assigned

Issue with the Computed name Property in a Component <template> <div class="person"> <p>{{name}}</p> </div> </template> <script> export default { name: 'person', data () { return ...

I am in need of a blank selection option using an md-select element, and I specifically do not want it to be

I'm currently utilizing Angular Material with md-select and I am in need of creating a blank option that, when selected, results in no value being displayed in the select dropdown. If this blank option is set as required, I would like it to return fal ...

Using iScroll without animation by using scrolltoelement on an iPhone PhoneGap application

I've been working on an iOS PhoneGap app that uses Backbone and some other libraries. To handle scrolling, I implemented iScroll which has been functioning properly. However, I encountered a problem with the following code snippet: events: { &apo ...

Anticipate await and fulfill promises

I'm encountering issues when attempting to refactor nested Promise.all's into async/await. It seems like there might be a misunderstanding in how I should be utilizing Promise.all and await. The goal is to iterate through an array, perform an ac ...

Adjusting the line-height in CSS dynamically based on the length of characters using jQuery

I am facing an issue with the Twitter widget on my website where our company's latest tweet sometimes gets cut off if it exceeds a certain length. I want to dynamically adjust the line-height CSS property of the element based on the tweet's chara ...

JavaScript - The progression of a virtual pet even when the user is offline

Currently, I am utilizing VueJS and MongoDB to develop an interactive virtual pet. Our approach involves storing user data in localStorage for easy access and retrieval. I'm exploring the concept of allowing the virtual pet to evolve autonomously (s ...

Clearing AsyncStorage in React Native

It has come to my attention that I am spending a significant amount of time debugging redux actions in react-native that are being persisted to AsyncStorage using redux-persist. There are instances where I wish I could simply clear AsyncStorage in order to ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Provide a unique <li> attribute for the JavaScript function to utilize

Is there a way to pass specific attributes from dropdown options to a javascript function? I have tried using .data() and .attr(), but the console keeps showing "undefined". Any suggestions on how to achieve this in a cleaner and simpler way would be gre ...

How to resolve: Preventing Ajax - Post request from executing repetitively

I am facing an issue with a table that is formatted using the Datatables script. There is a column in the table which contains icons for actions. When a user clicks on an icon, a modal is loaded and its content is fetched using the POST method. The modal ...

Ensure that the div remains fixed at the bottom even when multiple items are added

Following up on the previous question posted here: Sorting divs alphabetically in its own parent (due to many lists) I have successfully sorted the lists alphabetically, but now I need to ensure that a specific div with a green background (class: last) al ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

You cannot convert a function to a string while utilizing axios get in nuxtServerInit

While attempting to connect my app to the backend using Udemy's Nuxt.js course, I encountered a GET http://localhost:3000/ 500 (Internal Server Error) on the client side with the following code: import Vuex from 'vuex'; import axios from &a ...

Instructions for adding and deleting input text boxes on an ASP.NET master page

*I am currently facing an issue with adding and removing input textboxes for a CV form using ASP.NET in a master page. Whenever I click on the icon, it doesn't seem to work as intended. The idea is to have a textbox and an icon "+" to add more textbox ...