setup in Vue 3

insert image description here

foreword

With vue 3the release of , a lot of things have been added and changed, such as 响应式modifications, option Apichanges components Api, setupgrammatical sugar, etc., vue 3the release v2of v3. Closer to home, the protagonist of this article is nothing else, but the syntactic sugar v3that is super nice to use setup.

Introduction

setupis the compile-time one 单文件组件 (SFC)used in . This syntax is the default recommendation when using both and .组合式 API语法糖SFC组合式 API

Advantage:

  • Less boilerplate content, more concise code.
  • Ability to use pure TypeScriptdeclarative propsand custom events.
  • Better runtime performance (its template will be compiled into a rendering function in the same scope, avoiding the rendering context proxy object).
  • Better IDE type inference performance (reduced work for the language server to extract types from code).

use

<script setup>
...
</script>

In fact, v3when he first came out, he couldn't write like this. He needed to write like the following.

<script>
export default {
    
    
    setup () {
    
    
        const name = ''
        return {
    
    
            name
        }
    }
}
</script>

3.2Starting from the version of , we can SFCwrite in the file as we did at the beginning. This kind of photo is super convenient, we don't need to returngo out our methods and variables, but it should be noted that setupthere is no such thing in this thing this, why? Let's take a look at vuethe life cycle diagram.

image.png

We can see from the above figure that it will be executed later, and it has not yet been executed at this time setup, that is, before the component instance is created/parsed, it does not exist .renderervueinit Options Apithis

Related expansion

Components register to use

In the previous version, we need to introduce components and register them before they can be templateused in templates, but in setup, we don't need to register, we only need to import them to use them. But there is a disadvantage that the component cannot be renamed; the component name needs to be in the form of big hump; if you want to rename the component name, you can only write two scripttags to achieve it.

<template>
    <div>
        <span>我是父组件</span>
        <br />
        <Child></Child>
    </div>
</template>

<script setup>
import Child from "./components/child.vue"

</script>

image.png

Props

propsThe difference between this piece and that vue2is not very big, the parent component is still the same, but the child component has changed a bit. We need to definePropsdeclare what our parent component can pass in the child component props, and then we use it in the child component.

<template>
    <div>
        <span>我是子组件: {
    
    {
    
     message }}</span>
    </div>
</template>

<script setup>
import {
    
     defineProps } from 'vue';

const props = defineProps({
    
    
    message: {
    
    
        type: String,
        default: ''
    }
})

</script>

image.png

The reason for declaring a variable to receive it here definePropsis because templatethe template can be automatically parsed for us, but scriptit is not in the tag. If we need to use it scriptin don't need it.

console.log(message)

image.png

But we definePropscan get it if we get it through the received variable. It should be noted here that, as in the v2same, propsthe value subcomponents in cannot be changed.

console.log(props.message)

image.png

emit

emitEvent registration. Like propsthe same, you need to defineEmitsregister through. emit+ propsis vuea commonly used parent-child component communication method in .

This method accepts an array of event names, and specifies the event name and callback parameters when calling.

const emit = defineEmits(['init'])

setTimeout(() => {
    
    
    emit('init', 1222)
}, 2000);

parent component

<template>
    <div>
        <span>我是父组件</span>
        <br />
        <Child message="我是父组件传递的 msg 值" @init="init"></Child>
    </div>
</template>

<script setup>
import Child from "./components/child.vue"

const init = (event) => {
    
    
    console.log(event);
}

</script>

image.png

ref

This refis not that ref, here it is ref(引用). Don't get confused, gentlemen.

By refreference, we can easily manipulate and obtain variables or methods in subcomponents. We need to refdeclare it like a responsive one, and then mount and use it on the subcomponent.

<template>
    <div>
        <span>我是父组件</span>
        <br />
        <Child ref="myChild" message="我是父组件传递的 msg 值" ></Child>
    </div>
</template>

<script setup>
import Child from "./components/child.vue"

const myChild = ref(null)

</script>

Let's guess what the following code prints out.

setTimeout(()=>{
    
    
    console.log(myChild.value.name);
}, 1000)

It's time for all eyes to announce the long-awaited results and see if you guessed right.

The answer is: undefined.

image.png

In order to make you give up, I will show you the content of the subcomponents. I haven't changed it.

<template>
    <div>
        <span>我是子组件: {
    
    {
    
     message }}</span>
        <span>{
    
    {
    
     name }}</span>
    </div>
</template>

<script setup>
import {
    
     defineProps } from 'vue';

const props = defineProps({
    
    
    message: {
    
    
        type: String,
        default: ''
    }
})

const name = '我是子组件:张三'


</script>

Here we have to talk about the following defineExpose, and the judges will walk down together.

defineExpose

In vue3, if the things in our child components need to be called by the parent component, they need to be exposed before they can be called externally, otherwise it will be the same as the above example. ei, I need to intervene here, the exposure to templatethe outside world is not the same thing.

defineExpose({
    
    
    name
})

Now let's see again, is he still undefinedthere?

Ding dong, it's announced! It is not anymore undefined.

image.png

at last

The following figure is an enumeration of environments for writing this article.

  • vue3.2.45
  • vite4.0.2
  • @vitejs/plugin-vue4.0.0

vue3The above are setupsome related descriptions, if there are any deficiencies, you are welcome to correct and comment.

Guess you like

Origin blog.csdn.net/qq_44500360/article/details/128405532