官網現在有很貼心的 toggle 切換 Composition
Options
API
vue
規定好哪邊是 data, methods, computed, watch ...// Options API 範例
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
},
mounted() {
this.increment()
}
}
<script/>
<template>
Count is: {{ count }}
</template>
// Composition API 範例
<script>
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({ count: 0 })
function increment() {
state.count++
}
// increment 函數也要傳出去
return {
state,
increment
}
}
}
<script/>
<template>
<button @click="increment">
{{ state.count }}
</button>
</template>
語法糖寫法: 直接在 script 寫 setup
<script setup>
import { reactive } from 'vue'
const state = reactive({ count: 0 })
function increment() {
state.count++
}
</script>
<template>
<button @click="increment">
{{ state.count }}
</button>
</template>
index.html => main.js => App.vue
由大到小引入順序如何運作usexxx()
v-xxx="..."