vue-mounted process data data
The `mounted` method is a way to initialize data on Vue components.
When the Vue component is mounted into the DOM, the `mounted` method is triggered, which is usually used to obtain data, set initial state and other operations.
If you modify the `data` value in the `mounted` method, it may not take effect. This is because the `data` value is rendered when the `mounted` method is executed, and the `data` value is stored as responsive data in the Vue instance. When the `mounted` method is executed, the data in the template has been bound, so modifying the `data` value will not trigger view update.
If you want to modify the `data` value in the `mounted` method and trigger a view update, you can try the following:
1. How to use
Set the `data` value, which ensures that the modified value triggers view updates:
mounted() { (, 'key', 'newValue'); }
2.Vue3, you can use the set method
To set the `data` value:
mounted() { this.$ = 'newValue'; }
3.Vue2, you can try using this.$forceUpdate() method
Force update view:
mounted() { this.$forceUpdate(); }
But be aware that this approach may cause performance issues as it forces the view of the entire component to be updated.
4.Vue3, you can try to use the reactive method
Create a responsive object and modify the value in the object in the `mounted` method:
import { reactive } from 'vue'; export default { setup() { const state = reactive({ key: 'value', }); mounted() { = 'newValue'; } return { state, }; }, };
Ultimate way to deal with this.$nextTick
`this.$nextTick` is a method in the Vue instance that ensures that the callback function is executed after the next DOM update.
In Vue components, when you modify the data and want to update the view, you usually use the `this.$forceUpdate()` method. However, in some cases this can cause errors, such as when using the `this.$nextTick` method in computed properties.
When a Vue component renders, it compiles the template to the DOM and binds the data to the view. However, in some cases, such as in computed properties, the data may not have been bound to the view. In this case, if you try to modify the data directly in the computed properties, the view will not be updated.
To solve this problem, Vue provides the `this.$nextTick` method.
When you use the `this.$nextTick` method in your computed properties, it ensures that the callback function is executed after the next DOM update. In this way, the data will be bound to the view, achieving the desired effect.
Here is an example using this.$nextTick
<template> <div> <p>{{ message }}</p> <button @click="changeMessage">Change message</button> </div> </template> <script> export default { data() { return { message: 'Hello Vue!', }; }, methods: { changeMessage() { = 'Hello this.$nextTick!'; this.$nextTick(() => { ('Message has been updated'); }); }, }, }; </script>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.