[toc]

0x00 前言

学习记录一下 Vue 3.2 的 setup 语法。

0x01 如何使用setup语法糖

只需在 script 标签上写上 setup 就可以了。

代码如下(示例):

1
2
3
<template></template>

<script setup></script>

0x02 data 使用

setup 不需写 return,所以直接声明数据即可

代码如下(示例):

1
2
3
4
5
6
7
8
9
10
11
12
<script setup>
import { ref, reactive, toRefs } from "vue";

const data = reactive({
patternVisible: false,
debugVisible: false,
aboutExeVisible: false,
});

const content = ref("content");
const { patternVisible, debugVisible, aboutExeVisible } = toRefs(data);
</script>

0x03 method 使用

1
2
3
4
5
6
7
8
9
10
11
<template>
<button @click="clickButton">Clink button</button>
</template>

<script setup>
import { reactive } from "vue";

const clickButton = () => {
console.log(`Click button!`);
};
</script>

0x04 watchEffect 使用

1
2
3
4
5
6
7
8
9
10
<script setup>
import { ref, watchEffect } from "vue";

let sum = ref(0);

watchEffect(() => {
const x1 = sum.value;
console.log("watchEffect this.");
});
</script>

0x05 computed 使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script setup>
import { reactive, computed } from "vue";

let person = reactive({
firstName: "first",
lastName: "name",
});

person.fullName = computed(() => {
return person.firstName + "-" + person.lastName;
});

person.fullName = computed({
get() {
return person.firstName + "-" + person.lastName;
},
set(value) {
const nameArr = value.split("-");
person.firstName = nameArr[0];
person.lastName = nameArr[1];
},
});
</script>

0x06 props 使用

子组件代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<span>{{ props.name }}</span>
</template>

<script setup>
import { defineProps } from "vue";

const props = defineProps({
name: {
type: String,
default: "default name",
},
});
// or
//const props = defineProps(['name'])
</script>

父组件代码如下

1
2
3
4
5
6
7
8
9
10
<template>
<child :name="name" />
</template>

<script setup>
import { ref } from "vue";

import child from "./child.vue";
let name = ref("name");
</script>

0x07 emit 使用

子组件代码如下

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<button @click="chickButton">Click</button>
</template>
<script setup>
import { defineEmits } from "vue";

const emit = defineEmits(["changeVisible"]);

const isOk = () => {
emit("changeVisible");
};
</script>

父组件代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<Child @changeVisible="handleChangeVisible" />
</template>
<script setup>
import { reactive } from "vue";
import Child from "../components/Child";

const data = reactive({
visible: false,
});

const handleChangeVisible = () => {
data.visible = false;
};
</script>

0x08 await

setup 语法糖中可直接使用 await,即省略写 async。

参考 vue suspense

1
2
3
4
5
<script setup>
import Api from "../api/Api";
const data = await Api.getData();
console.log(data);
</script>

0x09 尾记

唔,大概就酱啦~

如果本文帮到了你,那就点赞或者打个赏吧,我才不会谢谢你,哼~

By 土豆豆,2022 年 9 月 19 日