前言
<script setup>语法是 vue 的单文件组件的写法。在开发 vue 的工程时,大部分使用的还是单文件组件的写法,写起来清晰明了。
内部数据
在 <script setup>顶层定义的变量都是内部数据,可以直接在模版中使用。
<template><div>{{count}}</div></template><script setup>import { ref } from "vue";const count = ref(0);</scirpt>
内部方法
方法和变量一样直接定义在顶层,就可以直接在模版中使用。
<template><div>{{count}}<button @click="add">加一</button></div></template><script setup>import { ref } from "vue";const count = ref(0);const add = () => {count.value++;}</scirpt>
外部数据
在 <script setup>中使用外部属性时,需要使用 defineProps编译宏,不需要引入,在 <script setup>直接使用即可。
用 defineProps宏定义的外部的属性,在模版中直接使用即可,在 <script setup>内部使用时需要拿到defineProps宏的返回值,所有的外部属性都在返回值里面。
<template><div>内部属性:{{count}}外部属性:{{title}}<button @click="add">加一</button></div></template><script setup>import { ref } from "vue";const count = ref(0);const props = defineProps(["title"])const add = () => {count.value++;}console.log("外部属性", props.title)</scirpt>
透传 Attributes
在 <script setup>中如果想访问透传的 attributes 的话,需要使用 useAttrs() API。
<script setup>import { useAttrs } from 'vue'const attrs = useAttrs();</script>
在 <script setup>中禁用 Attribute 继承的话,需要用到 defineOptions宏。
<script setup>defineOptions({inheritAttrs: false})</script>
抛出事件
在 <script setup>中抛出事件的话,需要使用 defineEmits宏,同样地不需要引入,在 <script setup>直接使用即可。
<template><div>内部属性:{{count}}外部属性:{{title}}<button @click="add">加一</button></div></template><script setup>import { ref } from "vue";const count = ref(0);const emit = defineEmits(['add-one']);const add = () => {count.value++;emit("add-one");}</scirpt>
使用组件
在 <script setup>如果是使用 app.component() 全局注册的组件的话,不用引入,直接使用即可。
如果是使用局部组件的话,需要在内部注册并使用。但在 <script setup>中,直接顶层引入组件,就会被自动注册组件。在模版中直接使用即可。
<template><div><ComponentA /></div></template><script setup>import ComponentA from "./ComponentA.vue";</script>
生命周期
<scirpt setup>的生命周期函数和 setup()函数的生命周期一样,都是从 Vue 里面获取对应的函数,传递回调执行。
<script setup>import { onMounted } from 'vue'onMounted(() => {console.log(`the component is now mounted.`)})</script>
暴露数据
在子组件使用 ref 属性的时候,可以直接拿到子组件的实例,此时可以访问子组件的一些数据和方法。但是 vue 规定 <script setup>的组件数据默认是私有的,通过一个子组件的实例无法访问 <script setup>的组件中的任何数据。除非子组件使用 defineExpose 宏显示将数据暴露出去,如下:
<template><div>内部属性:{{count}}</div></template><script setup>import { ref } from "vue";const count = ref(0);defineExpose({count,})</scirpt>
