1. script setup
< script setup > 是在单文件组件 (SFC) 中使用
组合式 API 的编译时语法糖
。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的 < script > 语法,它具有更多优势:
- 更少的样板内容,更
简洁
的代码。 - 能够使用
纯 TypeScript
声明 props 和自定义事件。 - 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
- 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。
script setup 写法
<template>
<div>
<h1>{{ msg }}</h1>
<button @click="handleBtnClick">{{ total }}点我加一</button>
</div>
</template>
<script setup>
import { ref } from "vue";
const msg = ref("hello world script setup 版本");
const total = ref(0);
const handleBtnClick = () => {
total.value++;
};
</script>
setup写法
<template>
<div>
<h1>{{ msg }}</h1>
<button @click="handleBtnClick">{{ total }}点我加一</button>
</div>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
const msg = ref("hello world setup 版本");
const total = ref(0);
const handleBtnClick = () => {
total.value++;
};
return {
msg,
total,
handleBtnClick,
};
},
};
</script>
差距还是蛮大的,现在一般都用
script setup
写法
2. 准备工作
先创建两个vue 文件,一个 setup 写法 ; 一个 script setup 写法。具体的代码在第一步中
然后再
app.vue
中,引入这俩组件,放在template 标签
里面,并且加上ref
<template>
<div>
<HelloSetup ref="helloSetup" />
<br />
<HelloScriptSetup ref="helloScriptSetup" />
</div>
</template>
<script setup>
import HelloSetup from "./views/03_script setup 做了什么操作/HelloSetup.vue";
import HelloScriptSetup from "./views/03_script setup 做了什么操作/HelloScriptSetup.vue";
import { onMounted, ref } from "vue";
const helloSetup = ref(null);
const helloScriptSetup = ref(null);
onMounted(() => {
console.log("helloScriptSetup", helloScriptSetup.value);
console.log("helloSetup", helloSetup.value);
});
</script>
<style scoped></style>
3. vite-plugin-inspect
vite-plugin-inspect
插件:可以通过这个插件直接查看模块的源代码
和编译后的代码
,从而更好地理解 Vite 的工作原理和模块的转换过程
- 安装包
npm i -D vite-plugin-inspect
- 更改
vite.config.ts
// vite.config.ts
import Inspect from 'vite-plugin-inspect'
export default {
plugins: [
Inspect()
],
}
- 重新运行项目
4. 两种写法对比
启动项目后,可以再控制台看到输出
script setup
的写法,是没有任何值的, 而setup
写法,是有东西的,相当于把这个组件的所有东西都暴露
出来了。
setup
写法编译出来的结果就是下面这样,其实没什么变化
script setup
的写法编译的结果如下。其实是多了一个__expose()
注意:
script setup
的写法 默认是有__expose()
这个方法的调用的,就会导致这个组件实例里面没有暴露任何东西
暴露什么东西,是可以自己控制的 和
data、watch 、method 同级有一个属性是
expose
,值是数组 ,这个可以配置要向外暴露那些东西setup
函数的第二个参数,是一个对象
,对象里面有expose
函数的,参数是一个对象script setup
写法中,defineExpose
函数,参数是一个对象,也可以配置要向外暴露那些东西
5. script setup 向外暴露指定的东西
<template>
<div>
<h1>{{ msg }}</h1>
<button @click="handleBtnClick">{{ total }}点我加一</button>
</div>
</template>
<script setup>
import { ref } from "vue";
const msg = ref("hello world script setup 版本");
const total = ref(0);
const handleBtnClick = () => {
total.value++;
};
defineExpose({
msg,
total,
handleBtnClick,
});
</script>
defineExpos
同样,编译后的代码也变了,再最后的编译代码中,其实没有
defineExpose
这个函数,还是会被处理成expose
,defineExpose
这个函数,再代码中不需要显示的导入