![]() |
VOOZH | about |
In VueJS, you may sometimes need to force a component to re-render, especially when the component doesn't update automatically due to Vue's reactivity system not detecting changes. One way to achieve this is by using a unique key attribute. Changing the key will force Vue to destroy and recreate the component, effectively re-rendering it.
If you haven't installed Vue CLI globally, you can do so with npm:
npm install -g @vue/cliCreate a new Vue project named force-re-render-example:
npm init vite@latest vue-rerender-example -- --template vueMove into the project directory:
cd force-re-render-example
npm install
Create a new file named RandomNumber.vue inside the src/components directory:
cd src/components/
touch RandomNumber.vue
"dependencies": {
"core-js": "^3.8.3",
"vue": "^3.2.13"
}
This Vue.js component displays a random number and includes a button to trigger a re-render. The random number is initialized in the data object and shown in the template. A method forceReRender() increments a componentKey to force a re-render, although the componentKey needs to be bound (e.g., :key="componentKey") for the re-render to take effect and update the random number. The component includes scoped styles for custom CSS.
Paste the following code into RandomNumber.vue. This component displays a random number and includes a button to force a re-render.
Open App.vue in the src directory and modify it to include the RandomNumber component.
Start the development server to see the component in action:
npm run serveOutput: