export default {
// ...
watch: {
key: {
handler() {},
flush: 'post'
}
}
}
what this code do?
can you give me some example?
I am learning vue.js by documentation and can't understand this code. so please help me understand
CodePudding user response:
The flush: 'post'
option means, that the handler is fired after vue has updated the component and has updated the Browser DOM.
Without this, the handler will be triggered directly when a value changes which does not necessarily means, that vue has already updated the component in the browser. If you want to perform a side effect that requires access to the DOM, you need to make sure, that vue has already done the update of the DOM
I would recommend to check out the lifecycle documentation in the vue documentation. This might give you an idea of how the lifecycle work in reactive frameworks.
Example
Imagine, you change a className based on a state variable. After you changed the class you want to know the height of your element. (The example is in Vue 3 composition API, but it works the same within the Vue 2 options api.)
export default defineComponent({
setup() {
const myElement = ref(null);
const someState = ref(false);
const rootClasses = computed(() => ({
'my-class': someState.value,
}))
const handleClick = () => {
someState.value = false;
}
watch(
someState,
(newSomeState) => {
if (!myElement.value || !newSomeState) return;
const height = myElement.offsetHeight;
// do something with the height here.
},
{ flush: 'post' }
);
}
})