前言

目标

  1. 了解script_setup的有哪些优点
  2. 掌握script_setup的语法

script_setup 1 基本语法 2 绑定后可直接在模版中使用 3 动态组件

script_setup

1.基本语法

<script setup> 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。
相比较于< script >,它有更多的优势:

  1. 更少的样板内容,更简洁的代码。
  2. 能够使用纯 TypeScript 声明 props 和自定义事件。
  3. 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
  4. 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。

写的时候 只需要在< script >后加上setup就可

<script setup>
console.log('hello script setup')
</script>
  • 1.
  • 2.
  • 3.

< script setup>只有在组件实例化被创建的时候执行一次

2.绑定后可直接在模版中使用

< script setup>会将其中的变量、函数声明,以及import导入的内容直接暴露给模版,在模版中直接就可以使用了。
变量 函数声明等在模版中直接使用

<script setup>
import { ref } from 'vue'

// 变量
const title= 'Hello!'
// 响应式变量
const count = ref(0)

// 函数
function log() {
  console.log(title)
}
</script>
// 在模版中直接使用
<template>
   <h2 id="h0">Count的值:{{ count  }}</h2>
  <button @click="log">{{ title }}</button>
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

importu引入、组件等在模版中直接使用

<script setup>
import { getDouble } from './utils/tools'
import myHelloworld from './HelloWorld.vue'
</script>
// 在模版中直接使用
<template>
   <h2 id="h1">{{ getDouble(100) }}</h2>
   <myHelloworld />
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

3 动态组件

<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>
<template>
  <component :is="Foo" />
  <component :is="someCondition ? Foo : Bar" />
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

参考链接
 script_setup