一、選項式
1、HTML寫法
<!--
跟 Vue 說 Hello World!
--><script type="module">
import { createApp } from 'vue'createApp({data() {return {message: 'Hello World!'}}
}).mount('#app')
</script><div id="app"><h1>{{ message }}</h1>
</div>
2、單文件組件SFC寫法
<!--
跟 Vue 說 Hello World!
--><script>
export default {data() {return {message: 'Hello World!'}}
}
</script><template><h1>{{ message }}</h1>
</template>
二、組合式
1、HTML寫法
<!--
跟 Vue 說 Hello World!
--><script type="module">
import { createApp, ref } from 'vue'createApp({setup() {// “ref”是用來存儲值的響應式數據源。// 理論上我們在展示該字符串的時候不需要將其包裝在 ref() 中,// 但是在下一個示例中更改這個值的時候,我們就需要它了。const message = ref('Hello World!')return {message}}
}).mount('#app')
</script><div id="app"><h1>{{ message }}</h1>
</div>
2、單文件組件SFC寫法
<!--
跟 Vue 說 Hello World!
--><script setup>
import { ref } from 'vue'// “ref”是用來存儲值的響應式數據源。
// 理論上我們在展示該字符串的時候不需要將其包裝在 ref() 中,
// 但是在下一個示例中更改這個值的時候,我們就需要它了。
const message = ref('Hello World!')
</script><template><h1>{{ message }}</h1>
</template>
3、<script setup>是語法糖,表示啟動組合式寫法
三、選項寫法和組合寫法的區別
1、比較<script>部分的區別
Vue2的選項式寫法:
<template><div><h1>PageA</h1><h1 v-text='num'></h1><button @click='add'>自增</button></div></template><script>export default {data() {return {num: 1}},methods: {add () {this.num++}}}
</script>
Vue3的setup選項式寫法:
<template><div><h1>PageA</h1><h1 v-text='num'></h1><button @click='add'>自增</button></div></template><script>// Vue3的選項寫法import { ref } from 'vue'export default {// data() {// return {// num: 1// }// },// methods: {// add () {// this.num++// }// }setup(props, context) {console.log('---props', props)console.log('---context', context)const num = ref(1)const add = () => {num.value++}// 一定要returnreturn {num,add}}}
</script>
2、選項式寫法對Vue2語法范式完全兼容,可以同時使用setup和選項,也可以只使用setup。
官方已經不推薦使用選項寫法了。
3、選項的寫法都有對應的組合API來替代。
4、setup選項
(1)setup選項相當于Vue2中的created(),可以理解成是組件生命周期的第一階段。
(2)setup的兩個參數
setup(props, context)
props:表示父組件傳過來的自定義屬性
context:表示上下文
(3)為什么在setup中要有一個上下文對象
因為在setup選項中沒有this。
例如父子組件通信,要把變量傳回父組件,用context.emit('input', num.value)代替this.$emit(xxx)
5、在Vue3中規避選項式寫法
在<script>上加setup,這種寫法是一種語法糖,是Vue3組合式寫法的語法糖。
<template><div><h1>PageB</h1><h1>{{ num }}</h1><button @click='add'>自增</button></div>
</template><script setup>// Vue3組合式寫法(并且是官方推薦的語法糖)import { ref } from 'vue'const num = ref(1000)const add = () => {num.value++}
</script>