setup script是vue3的一个语法糖
通常我们使用composition API的时候需要使用?setup 钩子,然后还要把页面上要使用的变量return返回出去,例如:
<template>
<div>{{name}}{{age}}{{persion}}</div>
<button @click="sayHello">说话</button>
<div>computed: {{ persion.fullName }}</div>
<div>{{ num }}</div>
<button @click="add">加1</button>
<div>{{ num2 }}</div>
<button @click="change">添-</button>
</template>
<script>
import { ref, reactive, computed } from 'vue'
export default {
name: 'HelloWorld',
setup() {
let name = ref('lyk')
let age = ref(18)
let num = ref(1)
let num2 = ref(2)
let persion = reactive({
firstName: '张',
lastName: '三'
})
persion.fullName = computed(() => {
return persion.firstName + '-' + persion.lastName
})
function sayHello() {
alert(`我叫${name.value},我${age.value}岁了,
${persion.firstName}---${persion.lastName}`)
}
function add() {
num.value++
num2.value++
}
function change() {
persion.firstName += '-'
persion.lastName += '+'
}
return {
name,
age,
persion,
sayHello,
num,
num2,
add,
change
}
}
}
</script>
<style scoped>
</style>
使用起来很麻烦。
<template>
<div>{{name}}{{age}}{{persion}}</div>
<button @click="sayHello">说话</button>
<div>computed: {{ persion.fullName }}</div>
<div>{{ num }}</div>
<button @click="add">加1</button>
<div>{{ num2 }}</div>
<button @click="change">添-</button>
</template>
<script setup>
import { ref, reactive, computed } from 'vue'
const name = ref('lyk')
const age = ref(18)
const num = ref(1)
const num2 = ref(2)
const persion = reactive({
firstName: '张',
lastName: '三'
})
persion.fullName = computed(() => {
return persion.firstName + '-' + persion.lastName
})
const sayHello = () => {
alert(`我叫${name.value},我${age.value}岁了,
${persion.firstName}---${persion.lastName}`)
}
const add = () => {
num.value++
num2.value++
}
const change = () => {
persion.firstName += '-'
persion.lastName += '+'
}
</script>
<style scoped>
</style>
这样就简单很多了。
现在来详细的说一下优点
- 组件不需要在components里注册,引入之后直接在页面上使用即可
- 属性方法不需要人return返回
- 新增了defineProps、defineEmit和useContext,但是useContext后来又被弃用了,用useSlots和useAttrs来代替,总共四个新的api,顾名思义defineProps充当props接受父组件的参数,defineEmit充当$emit自定义事件来给父组件传参,useSlots用于获取插槽数据,useAttrs可以获取到attrs的数据
// 首先是defineProps,父组件跟vue2完全没区别
// 子组件:
import { defineProps } from 'vue'
const props = defineProps({
xxx: {
type: xxx,
required: true/false
}
}) // 然后是defineEmits 父组件同样没区别
// 子组件:
import { defineEmits } from 'vue'
const emit = defineEmits('fn') // 先定义一个事件
const click = () => {
emit('fn', '参数') // 然后触发这个事件
}
|