script setup in vue3

script setup

< script setup > is a new syntax sugar from Vue3. The type is the suggestion in Vue's Git RFC. It should be made clear that this is not intended to completely replace any current writing. Its purpose is to provide developers with more concise syntax and simplify the lengthy template code when using the Composition API to write its single file component.

Without using < script setup >, our code is:

<template>
    <h1 v-text="count"></h1>
    <p v-text="double"></p>
    <button @click="add">count++</button>
</template>

<script>
    import { ref, unref, computed } from 'vue';
    export default {
      setup() {
        const count = ref(1);
        const double = computed(() => unref(count) * 2);
        function add() {
          count.value++;
        }
        return {
          count,
          double,
          add
        }
      }
    }
</script>

When we need to import a component, we not only need to import it explicitly in the file header, but also need to add a declaration in the components field. Moreover, if the variables declared in the setup need to be used by the template, they need to be returned explicitly at the end of the setup. If your component template uses few variables, this situation can be reluctantly accepted. However, when the variables and methods gradually increase, it is undoubtedly a boring thing to return after setup every time. You will also face great challenges when refactoring the code.

To solve this problem, vue3 added script setup syntax.

After using < script setup >, the same function is realized. The code is as follows:

<template>
	<h1 v-text="count"></h1>
	<p v-text="double"></p>
  <button @click="add">count++</button>
</template>

<script setup>
import { ref, unref, computed } from 'vue'

const count = ref(1)
const double = computed(() => unref(count) * 2)
function add() {
  count.value++
}
</script>

Not only the data, calculation attributes and methods, but also the instructions and components can be automatically obtained in our template, which is very magical

What is the meaning of using it?

To make a long story short, this syntax makes a single file component simpler.
In the original words of the RFC, "the main goal of this proposal is to reduce the verbosity of the use of the Composition API within SFC by directly exposing the context of < script setup > to the template."

This is what we just saw. We don't need to care about the value returned in the setup method (because sometimes we should forget to return the value we need in the setup, so the template can't get the corresponding value). We can simplify the code.

use

Component use

In script setup, component import is automatically registered:

<template>
  <Test :msg="msg"/>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Test from './components/test.vue'
const msg = ref('msg')
</script>

The component registration step is omitted, and there is no explicit action to export variables.

Use props & emit & usecontext

<template>
  <button @click="emit('setData', Number.parseInt(Math.random() * 10))">Add data</button>
</template>

<script setup>
    import { defineEmit, defineProps } from 'vue'
    // defineProps(['list'])
    const props = defineProps({
      list: {
        type: Array,
        default: () => []
      }
    })
    const emit = defineEmit(['deleteData', 'setData'])
    const { slots , attrs } = useContext()
</script>
  • Props needs to be defined by using defineProps. The usage is similar to that of props before

  • Emit uses defineEmit to define events that a component can emit

  • useContext accesses the slots and properties of the component

  • defineProps/defineEmit will make simple type inference based on the passed value

Define props – as the name suggests, it allows us to define props for components;

Define emits – defines the events that a component can emit

useContext – the slots and properties of the component can be accessed

instructions

Instructions are the same as components. They are automatically registered when imported.

<template>
  <div v-click-outside />
</template>

<script setup>
  import { directive as clickOutside } from 'v-click-outside'
</script>

inheritAttrs

<template inherit-attrs="false"></template>

The default value is true. In this case, the attribute bindings of the parent scope that are not recognized as props will be "fallback" and applied to the root element of the child component as an ordinary HTML attribute

await

If await is used, it needs to be used with suspend asynchronous component

/* Parent component */
<Suspense>
   <template #default>
     <AwaitComponent />
   </template>
   <template #fallback>
       loading....
   </template>
</Suspense>


<template>
  <h1>{{ result }}</h1>
</template>

<script lang="ts">
import { ref } from "vue";
const result = ref("")
function promiseFun () {
	return new Promise((resolve, reject) => {
		setTimeout(() => resolve('22322323'), 3000)
	})
}
result.value = await promiseFun()
</script>

vscode supporting plug-ins

Volar is a vscode plug-in to enhance the vue writing experience. Using volar plug-in can get the best support for script setup syntax.

To learn more about script setup, click?? This is a link

Keywords: Javascript Front-end Vue.js html

Added by e11rof on Wed, 09 Mar 2022 03:49:19 +0200