Home Vue3.2 <script setup> 實作 TodoMVC
Post
Cancel

Vue3.2 <script setup> 實作 TodoMVC

Vue3.2開始將 <script setup> 移除experimental status,和setup()區別在有許多 option API 有了替代方案,props, emit 也可以寫在 setup,variable 或 function 也不需要透過 return 才能讓 <template> 使用,哇!寫法怎麼好像有點既是感呢

下面會利用 TodoMVC 的練習,比較與統整 <script setup>setup() 常用的方法的差異。

TodoMVC 完整程式碼上傳至 Github (連結)。

data

setup()

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
import { ref } from 'vue';

export default {
    setup() {
        const newTodo = ref(undefined);

        return {
            newTodo,
        };
    },
}
</script>

<script setup>

宣告 ref 沒有差異,差在需不需要 return

1
2
3
4
5
<script setup>
import { ref } from 'vue';

const newTodo = ref(undefined);
</script>

component

1
2
3
<template>
    <TodoListEditor />
</template>

setup()

1
2
3
4
5
6
7
8
9
<script>
import TodoListEditor from 'components/TodoListEditor.vue';

export default {
    components: {
        TodoListEditor,
    },
}
</script>

<script setup>

import 之後就可以直接在 <template> 使用

1
2
3
<script setup>
import TodoListEditor from 'components/TodoListEditor.vue';
</script>

props

setup()

1
2
3
4
5
6
7
8
9
10
<script>
export default {
    props: {
        todoList: {
            required: true,
            type: Array,
        },
    },
}
</script>

<script setup>

defineProps 裡面內容與之前 props 相同

1
2
3
4
5
6
7
8
<script setup>
const props = defineProps({
    todoList: {
        required: true,
        type: Array,
    },
});
</script>

emit

setup()

1
2
3
4
5
6
7
8
9
10
<script>
export default {
    emits: ['remove:todo', 'update:todo'],
    setupt(props, {emit}) {
        function removeTodoItem(id){
            emit('remove:todo', id);
        }
    },
}
</script>

<script setup>

defineEmits 裡面內容與之前 emits 相同

1
2
3
4
5
6
7
<script setup>
const emit = defineEmits(['remove:todo', 'update:todo']);

function removeTodoItem(id){
    emit('remove:todo', id);
}
</script>

directive

directive是所有寫法中我最不適應的,底下是頁面載入時可以有 autofocus 的效果,可以根據不同 lifecyle 定義,利如 mouted

1
2
3
<input
    v-model="newTodo"
    v-focus>

setup()

1
2
3
4
5
6
7
8
9
10
11
<script>
const focus = {
    mounted: el => el.focus(),
};

export default {
    directives: {
        focus,
    },
}
</script>

<script setup>

1
2
3
4
5
<script setup>
const vFocus = {
    mounted: el => el.focus(),
};
</script>

lifecyle

基本上沒有什麼區別

setup()

1
2
3
4
5
6
7
8
9
10
11
<script>
import {onMounted} from 'vue';

export default {
    setup() {
        onMounted(() => {
            // to something
        });
    },
}
</script>

<script setup>

1
2
3
4
5
6
7
<script setup>
import {onMounted} from 'vue';

onMounted(() => {
    // to something
});
</script>
This post is licensed under CC BY 4.0 by the author.