筆記 - Vue.js Intro (2)

透過 Vue.js 官網 tutorial 學習的筆記。學習標的為 Vue 3, using composition API.

Lifecycle and Template Refs

Vue handles all the DOM updates by reactivity and declarative rendering.
But there will be cases where we need to manually work with the DOM.

Template Refs

Request a template ref, a reference to an element in the template, using the special ref attribute:

1
<p ref="p">hello</p>

Declare a ref with matching name to access the ref:

1
const p = ref(null)
  • The initial value of the ref is null, since the element does not exist yet when <script setup> is executed.
  • The template ref is only accessible after the component is mounted. 安裝/架設好

Lifecycle Hooks

Commonly used lifecycle hooks: onMounted, onUpdated, onUnmounted

Use onMounted() function to run code after mount.

1
2
3
4
5
import { ref, onMounted } from 'vue'
const p = ref(null)
onMounted(() => {
// component is now mounted
})

This is called a lifecycle hook - it allows us to register a callback to be called at certain times of the component’s lifecycle. There are other hooks such as onUpdated and onUnmounted.

See Lifecycle Hooks, Lifecycle Diagram, Composition API: Lifecycle Hooks

Watchers - watch() function

there are cases where we need to perform “side effects” in reaction to state changes - for example, mutating the DOM, or changing another piece of state based on the result of an async operation.

1
2
3
4
5
6
7
8
import { ref, watch } from 'vue'

const count = ref(0)

watch(count, (newCount) => {
// yes, console.log() is a side effect
console.log(`new count is: ${newCount}`)
})

watch() can directly watch a ref, and the callback gets fired whenever count’s value changes. watch() can also watch other types of data sources.

See Watchers