Vue3.2開始將 <script setup> 移除experimental status,和setup()區別在有許多 option API 有了替代方案,props, emit 也可以寫在 setup`,variable 或 function 也不需要透過 return 才能讓 <template> 使用,哇!寫法怎麼好像有點既是感呢
下面會利用 TodoMVC 的練習,比較與統整 <script setup> 和 setup() 常用的方法的差異。
data
setup
<script> import { ref } from 'vue'; export default { setup() { const newTodo = ref(undefined); return { newTodo, }; }, } </script>
<script setup>
宣告 ref 沒有差異,差在需不需要 return<script setup> import { ref } from 'vue'; const newTodo = ref(undefined); </script>
component
<template> <TodoListEditor /> </template>
setup
<script> import TodoListEditor from 'components/TodoListEditor.vue'; export default { components: { TodoListEditor, }, } </script>
<script setup>
import 之後就可以直接在 <template> 使用<script setup> import TodoListEditor from 'components/TodoListEditor.vue'; </script>
props
setup
<script> export default { props: { todoList: { required: true, type: Array, }, }, } </script>
<script setup>
defineProps 裡面內容與之前 props 相同<script setup> const props = defineProps({ todoList: { required: true, type: Array, }, }); </script>
emit
setup
<script> export default { emits: ['remove:todo', 'update:todo'], setupt(props, {emit}) { function removeTodoItem(id){ emit('remove:todo', id); } }, } </script>
<script setup>
defineEmits 裡面內容與之前 emits 相同<script setup> const emit = defineEmits(['remove:todo', 'update:todo']); function removeTodoItem(id){ emit('remove:todo', id); } </script>
directive
directive是所有寫法中我最不適應的,底下是頁面載入時可以有 autofocus 的效果,可以根據不同 lifecyle 定義,利如 mouted<input v-model="newTodo" v-focus>
setup
<script> const focus = { mounted: el => el.focus(), }; export default { directives: { focus, }, } </script>
<script setup>
<script setup> const vFocus = { mounted: el => el.focus(), }; </script>
lifecycle
基本上沒有什麼區別setup
<script> import {onMounted} from 'vue'; export default { setup() { onMounted(() => { // to something }); }, } </script>
<script setup>
<script setup> import {onMounted} from 'vue'; onMounted(() => { // to something }); </script>