今天來介紹比較容易混淆的部分
let id = 0
const hideCompleted = ref(false)
const todos = ref([
{ id: id++, text: 'Learn HTML', done: true },
{ id: id++, text: 'Learn JavaScript', done: true },
{ id: id++, text: 'Learn Vue', done: false }
])
const filteredTodos = computed(() => {
return hideCompleted.value
? todos.value.filter((t) => !t.done)
: todos.value
})
理論上可以像下面直接寫在template裡,若遇到要重複使用的話,可以改成呼叫function來減少冗長的程式碼,但是這些都不像computed有快取功能,不會只在有變動時才執行
{{ hideCompleted.value
? todos.value.filter((t) => !t.done)
: todos.value }}
const todoId = ref(1)
const data = ref(null)
watchEffect(async () => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
)
data.value = await response.json()
})
const todoId = ref(1)
const data = ref(null)
watch(
todoId,
async () => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
)
data.value = await response.json()
},
{ immediate: true }
)
//ChildComp.vue
<script setup>
const props = defineProps({
msg: String
})
</script>
<template>
<h2>{{ msg || 'No props passed yet' }}</h2>
</template>
2.在父組件使用,並傳入參數
//ParentComp.vue
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const greeting = ref('Hello from parent')
</script>
<template>
// 使用:<prop name>指定傳入參數
<ChildComp :msg="greeting" />
</template>
//ChildComp.vue
<script setup>
const emit = defineEmits(['response'])
emit('response', 'hello from child')
</script>
<template>
<h2>Child component</h2>
</template>
2.在父組件接收通知
//ParentComp.vue
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const childMsg = ref('No child msg yet')
</script>
<template>
<ChildComp @response="(msg) => childMsg = msg" />
<p>{{ childMsg }}</p>
</template>
使用prop + emit就是俗稱的雙向綁定
這裡跟prop不同的是,slot其實是在父組件範圍處理的,所以不需要emit。
slot還有更多進階用法,可以參考這篇
//ChildComp.vue
<template>
<slot>Fallback content</slot>
</template>
2.在父組件取代掉<slot></slot>
//ParentComp.vue
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const msg = ref('from parent')
</script>
<template>
<ChildComp>Message: {{ msg }}</ChildComp>
</template>
在不考慮options API的情況下,有以下幾個階段:
大多數常見的網頁互動與畫面變化,通常都發生在這個階段
框架 | Vue | React |
---|---|---|
計算 | computed | useMemo |
副作用 | watch, watchEffect | useEffect |
進入倦怠期