VUE3-life cycle hook "six"

Table of contents

1.onMounted()

2.onUpdated()

The role of the life cycle is to actively execute certain programs when the page is loaded. There are many kinds of life cycle hooks, each of which is in order. If they are not executed in order, certain effects will not be triggered, so you must first understand the order of life cycle hook functions.

The following is the life cycle diagram provided by the official website

It says that there are two main life cycle hooks, onMounted and onUpdated

Combined API: Lifecycle Hooks | Vue.js  official website also has other introductions to lifecycle hooks.

1.onMounted()

It is a bit later than setup, setup is executed first, and after onMounted. It can be understood that in the setup, the sequence in the setup is executed sequentially from top to bottom. When all the codes in the setup are executed, then onMounted is executed immediately, which can be used for operations after page initialization, such as the role of the bullet box etc.

the code

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	console.log('setup启动')

	const a = ref('onMounted启动')
	onMounted(() => {
		console.log(a.value)
	})
	console.log('setup启动11')
</script>

<template>

</template>

Effect

2.onUpdated()

Triggered when the bound data changes.

the code

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

	const count = ref(0)
	onUpdated(() => {
		// 文本内容应该与当前的 `count.value` 一致  document.getElementById('count').textContent
		console.log('onUpdated:' + count.value)
	})
</script>

<template>
	<input v-model="count" />
</template>

Effect 

This is somewhat similar to the effect of a listener watch, but there are still differences between the two.

onUpdated

1. Every time there is a corresponding data update, it will enter this method to execute the same code.

2. Before executing it, variables and interfaces have changed.

watch

1. Only monitor the value of the variable you wrote.

2. It will only listen when the data changes.

Guess you like

Origin blog.csdn.net/u012563853/article/details/128439308