Vue-Composition API(Props)

小知識。

簡述

要在 setup 中存取 props 的方式很簡單,就是透過 setup(props) 來拿到這個參數就行了。

來看一個範例,假設我們有一個頁面長這樣:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<template>
<div class="home">
<div v-for="post of posts" :key="post.title">
<!-- 傳入 props -->
<SinglePost :post="post" />
</div>
</div>
</template>

<script>
import SinglePost from '../components/SinglePost.vue'

export default {
components: { SinglePost },
setup() {
const posts = [
{
title: 'CSS Top 5 tricks',
body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt culpa nulla harum officia vitae. Fugit deserunt similique neque? Molestias, enim! Quidem obcaecati esse blanditiis dicta facilis voluptate magni non similique!'
},
{
title: 'TypeScript Tutorial',
body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt culpa nulla harum officia vitae. Fugit deserunt similique neque? Molestias, enim! Quidem obcaecati esse blanditiis dicta facilis voluptate magni non similique!'
}
]
return { posts }
}
}
</script>

這邊想要把 posts 當成 props 傳給 <SinglePost />,來看要怎麼做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div class="post-list">
<h2>{{ post.title }}</h2>
<p>{{ bodySnippet }}</p>
</div>
</template>

<script>
import { computed } from '@vue/runtime-core'
export default {
// 這個一樣要寫出來,template 才有辦法用
props: ['post'],
// 接收 props
setup(props) {
const bodySnippet = computed(() => props.post.body.substring(0, 100) + '...')
return { bodySnippet }
}
}
</script>

這邊要特別注意的地方就是 props 屬性的部分,如果是 <template> 會用到的「那種 props」的話就得列出來,反之則不用(不過應該很少這種情況啦)。

Vue-Composition API(Life Cycle Hooks) Vue-Composition API(watch & watchEffect)
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×