Skip to content

setup 语法糖

.vue 文件的 script 开始标签上可加入 setup 语法糖,代码如下:

vue
<script setup>
console.log('hello script setup')
</script>

里面的代码会被编译成组件 setup() 函数的内容。这意味着与普通的 <script> 只在组件被首次引入的时候执行一次不同,<script setup> 中的代码会在 每次组件实例被创建的时候执行

数据与方法

使用 setup 语法糖后,在 script 标签内定义的数据、方法可以在模板中直接使用。

vue
<template>
    <h3>姓名:{{ form.name }}</h3>
    <h3>年龄:{{ form.age }}</h3>
    <button @click="addAge">Age++</button>
</template>

<script setup>
import { reactive } from "vue";
const form = reactive({
    name: 'iGma',
    age: 20
});

const addAge = () => {
    form.age++;
}
</script>

自定义组件

使用 setup 语法糖后,引入自定义组件无需注册,引入后在模板中即可使用。

vue
<template>
    <Hello />
</template>

<script setup>
import Hello from "co/Hello.vue";
</script>

注:引入组件时使用的路径小编在 vite.config.js 中借助 path 包已经配置过了,这里就不展示了。

props 传参

父组件向子组件传参,可以直接写在子组件身上。

子组件使用 defineProps 接参,无需引入。

vue
<template>
	<Hello :form="form" />
</template>
vue
<template>
    <h3>姓名:{{ form.name }}</h3>
    <h3>年龄:{{ form.age }}</h3>
    <h3>性别:{{ form.gender ? '男' : '女' }}</h3>
    <button @click="form.age++">age++</button>
</template>

<script setup>
const props = defineProps({
    form: Object
});
</script>

上面代码中我们指定了 form 的类型,除此以外还可以指定必要性和默认值,代码如下:

vue
<script setup>
import { reactive } from "vue";
const props = defineProps({
    form: {
        type: Object,       // 类型
        required: false,    // 是否必传
        default: reactive({
            name: 'xxx',
            age: 10,
            gender: 0
        })
    }
});
</script>

emit 传参

子组件可以通过 defineEmits 注册自定义事件,通过事件向父组件传递数据

vue
<template>
    <button @click="submit">向父组件传递数据</button>
</template>

<script setup>
const emit = defineEmits(['submit']);
const submit = () => {
    emit('submit', '我是子组件传递的数据');
}
</script>

父组件中在子组件身上绑定自定义事件 submit

vue
<template>
	<Hello @submit="submit" />
</template>

<script setup>
import Hello from "co/Hello.vue";
const submit = e => {
	console.log(e);	// 输出:我是子组件传递的数据
}
</script>

基于 MIT 许可发布