Table of Contents
script setup syntax sugar
Basic use
Component life cycle
组件自动注册
定义组件的 props
defineProps ----> [用来接收父组件传来的 props] 代码示列
定义 emit
defineEmit ----> [子组件向父组件事件传递]
父子组件通信
useSlots() 和 useAttrs()
获取 slots 和 attrs
defineExpose API
defineExpose ----> [组件暴露出自己的属性]
watchEffect和watch区别
reactive
ref 暴露变量到模板
其他 Hook Api
支持 async await 异步
定义组件其他配置
Home Web Front-end Vue.js A detailed explanation of script setup syntactic sugar in Vue3

A detailed explanation of script setup syntactic sugar in Vue3

Nov 22, 2022 pm 08:07 PM
front end vue.js

A detailed explanation of script setup syntactic sugar in Vue3

script setup syntax sugar

Combined API: setup()

Basic use

In the Composition API series of Vue 3, a new setup function is introduced, which is a component option and is executed before creating the component. , once the props are parsed and serve as the entry point to the composed API. [Learning video sharing: vue video tutorial, web front-end video]

setup option is a receiving props and context functions, we refer to the documentation for discussion. Additionally, we expose everything returned by setup to the rest of the component (computed properties, methods, lifecycle hooks, etc.) as well as the component's template.

<script>
// 这是一个基于 TypeScript 的 Vue 组件
import { defineComponent } from &#39;vue&#39;

export default defineComponent({
  setup(props, context) {
    // 在这里声明数据,或者编写函数并在这里执行它

    return {
      // 需要给 `<template />` 用的数据或函数,在这里 `return` 出去
    }
  },
})

</script>
Copy after login

The new setup option is executed before the component is created, after props is parsed, and is the entrance to the combined API.

Note:
You should avoid using this in setup because it will not find the component instance. The call to setup occurs before the data property, computed property or methods are parsed, so they cannot> be used in setup was obtained.

In the script tag with setup added, we don’t have to declare and methods. This writing method will automatically expose all top-level variables and functions to the template (template ) Use
here to emphasize the sentence " Exposed to the template is not the same thing as exposed to the outside "

TIP: said To put it more simply, when using the Vue 3 life cycle, the entire component-related business code can be executed in setup.

Because other life cycles will be enabled after setup, let’s compare the changes in the Vue3 life cycle of Vue2

Component life cycle

About the changes in the Vue life cycle, you can intuitively understand it from the following table:

##beforeMountonBeforeMountExecuted before the component is mounted on the nodemountedonMountedExecuted after the component is mountedbeforeUpdateonBeforeUpdatePerformed before component updateupdatedonUpdatedComponent update Execute after completionbeforeDestroyonBeforeUnmountExecute before component uninstallationdestroyedonUnmountedExecuted after component unmounting is completederrorCapturedonErrorCapturedActivated when catching an exception from a descendant component Hook function

可以看到 Vue 2 生命周期里的 beforeCreatecreated ,在 Vue 3 里已被 setup 替代。

script setup 语法糖

它是 Vue3 的一个新语法糖,在 setup 函数中。所有 ES 模块导出都被认为是暴露给上下文的值,并包含在 setup() 返回对象中。相对于之前的写法,使用后,语法也变得更简单。

自动注册属性和方法无需返回,直接使用

1.<script setup> 语法糖并不是新增的功能模块,它只是简化了以往的组合API(compositionApi)的必须返回(return)的写法,并且有更好的运行时性能。

2.在 setup 函数中:所有 ES 模块导出都被认为是暴露给上下文的值,并包含在 setup() 返回对象中。相对于之前的写法,使用后,语法也变得更简单。

你不必担心setup语法糖的学习成本,他是组合式API的简化,并没有新增的知识点。你只需要了解一些用法和细微的不同之处,甚至比之前写setup()还要顺手!

使用方式也很简单,只需要在 script 标签加上 setup 关键字即可

<script setup>
</script>
Copy after login

组件核心 API 的使用

组件自动注册

在 script setup 中,引入的组件可以直接使用,无需再通过components进行注册,并且无法指定当前组件的名字,它会自动以文件名为主,也就是不用再写name属性了。

示例

<template>
	<Child />
</template>

<script setup>
import Child from &#39;@/components/Child.vue&#39;
</script>
Copy after login

定义组件的 props

defineProps ----> [用来接收父组件传来的 props] 代码示列

通过defineProps指定当前 props 类型,获得上下文的props对象。

示例:

<script setup>
  import { defineProps } from &#39;vue&#39;

  const props = defineProps({
    title: String,
  })
</script>
<!-- 或者 -->
<script setup> 
    import { ref,defineProps } from &#39;vue&#39;;
    
    type Props={ 
        msg:string 
    }
    defineProps<Props>(); 
</script>
Copy after login

定义 emit

defineEmit ----> [子组件向父组件事件传递]

使用defineEmit定义当前组件含有的事件,并通过返回的上下文去执行 emit。

代码示列

<script setup>
  import { defineEmits } from &#39;vue&#39;
  const emit = defineEmits([&#39;change&#39;, &#39;delete&#39;])
  
</script>
Copy after login

父子组件通信

defineProps 用来接收父组件传来的 props ; defineEmits 用来声明触发的事件。

//父组件
<template>
	<Child @getChild="getChild" :title="msg" />
</template>

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;@/components/Child.vue&#39;
const msg = ref(&#39;parent value&#39;)
const getChild = (e) => {
	// 接收父组件传递过来的数据
	console.log(e); // child value
}
</script>
Copy after login
//子组件
<template>
	<div @click="toEmits">Child Components</div>
</template>

<script setup>
// defineEmits,defineProps无需导入,直接使用
const emits = defineEmits([&#39;getChild&#39;]);
const props = defineProps({
	title: {
		type: String,
		defaule: &#39;defaule title&#39;
	}
});

const toEmits = () => {
	emits(&#39;getChild&#39;, &#39;child value&#39;) // 向父组件传递数据
}

// 获取父组件传递过来的数据
console.log(props.title); // parent value
</script>
Copy after login

子组件通过 defineProps 接收父组件传过来的数据,子组件通过 defineEmits 定义事件发送信息给父组件

useSlots()useAttrs()

获取 slots 和 attrs

注:useContext API 被弃用,取而代之的是更加细分的 api。

可以通过useContext从上下文中获取 slots 和 attrs。不过提案在正式通过后,废除了这个语法,被拆分成了useAttrsuseSlots

  • useAttrs:见名知意,这是用来获取 attrs 数据,但是这和 vue2 不同,里面包含了 class属性方法

<template>
    <component v-bind=&#39;attrs&#39;></component>
</template>
<srcipt setup>
   const attrs = useAttrs();
<script>
Copy after login
  • useSlots: 顾名思义,获取插槽数据。

使用示例:

// 旧
<script setup>
  import { useContext } from &#39;vue&#39;

  const { slots, attrs } = useContext()
</script>

// 新
<script setup>
  import { useAttrs, useSlots } from &#39;vue&#39;

  const attrs = useAttrs()
  const slots = useSlots()
</script>
Copy after login

defineExpose API

defineExpose ----> [组件暴露出自己的属性]

传统的写法,我们可以在父组件中,通过 ref 实例的方式去访问子组件的内容,但在 script setup 中,该方法就不能用了,setup 相当于是一个闭包,除了内部的 template模板,谁都不能访问内部的数据和方法。

<script setup> 的组件默认不会对外部暴露任何内部声明的属性。
如果有部分属性要暴露出去,可以使用 defineExpose

注意:目前发现defineExpose暴露出去的属性以及方法都是 unknown 类型,如果有修正类型的方法,欢迎评论区补充。

如果需要对外暴露 setup 中的数据和方法,需要使用 defineExpose API。示例

//子组件

<template>
	{{msg}}
</template>

<script setup>
import { ref } from &#39;vue&#39;

let msg = ref("Child Components");
let num = ref(123);

// defineExpose无需导入,直接使用
defineExpose({
	msg,
	num
});
</script>
Copy after login
//父组件
<template>
	<Child ref="child" />
</template>

<script setup>
import { ref, onMounted } from &#39;vue&#39;
import Child from &#39;@/components/Child.vue&#39;

let child = ref(null);

onMounted(() => {
	console.log(child.value.msg); // Child Components
	console.log(child.value.num); // 123
})
</script>
Copy after login

定义响应变量、函数、监听、计算属性computed

<script setup > 
import { ref,computed,watchEffect } from &#39;vue&#39;;

const count = ref(0); //不用 return ,直接在 templete 中使用

const addCount=()=>{ //定义函数,使用同上 
    count.value++; 
} 

//创建一个只读的计算属性 ref:
const plusOne = computed(() => count.value + 1)

// 创建一个可写的计算属性 ref
const plusOne = computed({
get: () => count.value + 1, 
set: (val) => { count.value = val - 1 } 
})


//定义监听,使用同上 //...some code else 
watchEffect(()=>console.log(count.value)); 
</script>
Copy after login

watchEffect和watch区别

1、watch是惰性执行,也就是只有监听的值发生变化的时候才会执行,但是watchEffect不同,每次代码加载watchEffect都会执行(忽略watch第三个参数的配置,如果修改配置项也可以实现立即执行)

2、watch需要传递监听的对象,watchEffect不需要

3、watch只能监听响应式数据:ref定义的属性和reactive定义的对象,如果直接监听reactive定义对象中的属性是不允许的,除非使用函数转换一下

4、watchEffect如果监听reactive定义的对象是不起作用的,只能监听对象中的属性。

reactive

返回一个对象的响应式代理。

<script setup>
import { reactive, onUnmounted } from &#39;vue&#39;

const state = reactive({
    counter: 0
})
// 定时器 每秒都会更新数据
const timer = setInterval(() => {
    state.counter++
}, 1000);

onUnmounted(() => {
    clearInterval(timer);
})
</script>
<template>
    <div>{{state.counter}}</div>
</template>
Copy after login

使用ref也能达到我们预期的'counter',并且在模板中,vue进行了处理,我们可以直接使用counter而不用写counter.value.

ref和reactive的关系:

ref是一个{value:'xxxx'}的结构,value是一个reactive对象

ref 暴露变量到模板

曾经的提案中,如果需要暴露变量到模板,需要在变量前加入export声明:

export const count = ref(0)
Copy after login

不过在新版的提案中,无需export声明,编译器会自动寻找模板中使用的变量,只需像下面这样简单的声明,即可在模板中使用该变量

<script setup >
import { ref } from &#39;vue&#39;

const counter = ref(0);//不用 return ,直接在 templete 中使用

const timer = setInterval(() => {
    counter.value++
}, 1000)

onUnmounted(() => {
    clearInterval(timer);
})
</script>
<template>
    <div>{{counter}}</div>
</template>
Copy after login

其他 Hook Api

  • useCSSModule:CSS Modules 是一种 CSS 的模块化和组合系统。vue-loader 集成 CSS Modules,可以作为模拟 scoped CSS。允许在单个文件组件的setup中访问CSS模块。此 api 本人用的比较少,不过多做介绍。

  • useCssVars: 此 api 暂时资料比较少。介绍v-bind in styles时提到过。

  • useTransitionState: 此 api 暂时资料比较少。

  • useSSRContext: 此 api 暂时资料比较少。

支持 async await 异步

注意在vue3的源代码中,setup执行完毕,函数 getCurrentInstance 内部的有个值会释放对 currentInstance 的引用,await 语句会导致后续代码进入异步执行的情况。所以上述例子中最后一个 getCurrentInstance() 会返回 null,建议使用变量保存第一个 getCurrentInstance() 返回的引用.

<script setup>
  const post = await fetch(`/api/post/1`).then((r) => r.json())
</script>
Copy after login

<script setup> 中可以使用顶层 await。结果代码会被编译成 async setup()

<script setup>
const post = await fetch(`/api/post/1`).then(r => r.json())
</script>
Copy after login

另外,await 的表达式会自动编译成在 await 之后保留当前组件实例上下文的格式。

注意
async setup() 必须与 Suspense 组合使用,Suspense 目前还是处于实验阶段的特性。我们打算在将来的某个发布版本中开发完成并提供文档 - 如果你现在感兴趣,可以参照 tests 看它是如何工作的。

定义组件其他配置

配置项的缺失,有时候我们需要更改组件选项,在setup中我们目前是无法做到的。我们需要在上方再引入一个 script,在上方写入对应的 export即可,需要单开一个 script。

<script setup> 可以和普通的 <script> 一起使用。普通的 <script> 在有这些需要的情况下或许会被使用到:

  • 无法在 <script setup> 声明的选项,例如 inheritAttrs 或通过插件启用的自定义的选项。
  • 声明命名导出。
  • 运行副作用或者创建只需要执行一次的对象。

在script setup 外使用export default,其内容会被处理后放入原组件声明字段。

<script>
// 普通 `<script>`, 在模块范围下执行(只执行一次)
runSideEffectOnce()

// 声明额外的选项
  export default {
    name: "MyComponent",
    inheritAttrs: false,
    customOptions: {}
  }
</script>
<script setup>
    import HelloWorld from &#39;../components/HelloWorld.vue&#39;
    // 在 setup() 作用域中执行 (对每个实例皆如此)
    // your code
</script>
<template>
  <div>
    <HelloWorld msg="Vue3 + TypeScript + Vite"/>
  </div>
</template>
Copy after login

注意:Vue 3 SFC 一般会自动从组件的文件名推断出组件的 name。在大多数情况下,不需要明确的 name 声明。唯一需要的情况是当你需要 <keep-alive> 包含或排除或直接检查组件的选项时,你需要这个名字。

(Обучающее видеообмен: разработка веб-интерфейса, Видео по основам программирования)

The above is the detailed content of A detailed explanation of script setup syntactic sugar in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

C# development experience sharing: front-end and back-end collaborative development skills C# development experience sharing: front-end and back-end collaborative development skills Nov 23, 2023 am 10:13 AM

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

How to implement instant messaging on the front end How to implement instant messaging on the front end Oct 09, 2023 pm 02:47 PM

Methods for implementing instant messaging include WebSocket, Long Polling, Server-Sent Events, WebRTC, etc. Detailed introduction: 1. WebSocket, which can establish a persistent connection between the client and the server to achieve real-time two-way communication. The front end can use the WebSocket API to create a WebSocket connection and achieve instant messaging by sending and receiving messages; 2. Long Polling, a technology that simulates real-time communication, etc.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: explore how Golang plays a role in the front-end field Combination of Golang and front-end technology: explore how Golang plays a role in the front-end field Mar 19, 2024 pm 06:15 PM

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn

See all articles
Vue 2 life cycleVue 3 life CycleExecution time description
beforeCreatesetupExecution before component creation
createdsetupExecuted after the component is created