前言

<script setup>语法是 vue 的单文件组件的写法。在开发 vue 的工程时,大部分使用的还是单文件组件的写法,写起来清晰明了。

内部数据

<script setup>顶层定义的变量都是内部数据,可以直接在模版中使用。

  1. <template>
  2. <div>
  3. {{count}}
  4. </div>
  5. </template>
  6. <script setup>
  7. import { ref } from "vue";
  8. const count = ref(0);
  9. </scirpt>

内部方法

方法和变量一样直接定义在顶层,就可以直接在模版中使用。

  1. <template>
  2. <div>
  3. {{count}}
  4. <button @click="add">加一</button>
  5. </div>
  6. </template>
  7. <script setup>
  8. import { ref } from "vue";
  9. const count = ref(0);
  10. const add = () => {
  11. count.value++;
  12. }
  13. </scirpt>

外部数据

<script setup>中使用外部属性时,需要使用 defineProps编译宏,不需要引入,在 <script setup>直接使用即可。
defineProps宏定义的外部的属性,在模版中直接使用即可,在 <script setup>内部使用时需要拿到defineProps宏的返回值,所有的外部属性都在返回值里面。

  1. <template>
  2. <div>
  3. 内部属性:{{count}}
  4. 外部属性:{{title}}
  5. <button @click="add">加一</button>
  6. </div>
  7. </template>
  8. <script setup>
  9. import { ref } from "vue";
  10. const count = ref(0);
  11. const props = defineProps([
  12. "title"
  13. ])
  14. const add = () => {
  15. count.value++;
  16. }
  17. console.log("外部属性", props.title)
  18. </scirpt>

透传 Attributes

<script setup>中如果想访问透传的 attributes 的话,需要使用 useAttrs() API。

  1. <script setup>
  2. import { useAttrs } from 'vue'
  3. const attrs = useAttrs();
  4. </script>

<script setup>中禁用 Attribute 继承的话,需要用到 defineOptions宏。

  1. <script setup>
  2. defineOptions({
  3. inheritAttrs: false
  4. })
  5. </script>

抛出事件

<script setup>中抛出事件的话,需要使用 defineEmits宏,同样地不需要引入,在 <script setup>直接使用即可。

  1. <template>
  2. <div>
  3. 内部属性:{{count}}
  4. 外部属性:{{title}}
  5. <button @click="add">加一</button>
  6. </div>
  7. </template>
  8. <script setup>
  9. import { ref } from "vue";
  10. const count = ref(0);
  11. const emit = defineEmits(['add-one']);
  12. const add = () => {
  13. count.value++;
  14. emit("add-one");
  15. }
  16. </scirpt>

使用组件

<script setup>如果是使用 app.component() 全局注册的组件的话,不用引入,直接使用即可。
如果是使用局部组件的话,需要在内部注册并使用。但在 <script setup>中,直接顶层引入组件,就会被自动注册组件。在模版中直接使用即可。

  1. <template>
  2. <div>
  3. <ComponentA />
  4. </div>
  5. </template>
  6. <script setup>
  7. import ComponentA from "./ComponentA.vue";
  8. </script>

生命周期

<scirpt setup>的生命周期函数和 setup()函数的生命周期一样,都是从 Vue 里面获取对应的函数,传递回调执行。

  1. <script setup>
  2. import { onMounted } from 'vue'
  3. onMounted(() => {
  4. console.log(`the component is now mounted.`)
  5. })
  6. </script>

暴露数据

在子组件使用 ref 属性的时候,可以直接拿到子组件的实例,此时可以访问子组件的一些数据和方法。但是 vue 规定 <script setup>的组件数据默认是私有的,通过一个子组件的实例无法访问 <script setup>的组件中的任何数据。除非子组件使用 defineExpose 宏显示将数据暴露出去,如下:

  1. <template>
  2. <div>
  3. 内部属性:{{count}}
  4. </div>
  5. </template>
  6. <script setup>
  7. import { ref } from "vue";
  8. const count = ref(0);
  9. defineExpose({
  10. count,
  11. })
  12. </scirpt>