前端基础之《Vue(26)—Vue3两种语法范式》
一、选项式
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) {const num = ref(1)const add = () => {num.value++}// 一定要return,抛出去return {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><h1>PageB</h1><h1>{{ num }}</h1><button @click='add'>自增</button>
</template><script setup>// Vue3组合式写法(并且是官方推荐的语法糖)import { ref } from 'vue'const num = ref(1000)const add = () => {num.value++}
</script>