6
Author: Matt Maribojoc
Translator: Frontend Xiaozhi
Source: stackabuse
If you have dreams and dry goods, search for [Great Move to the World] Follow this brushing wit who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

If you have recently worked with Vite and Vue3, you will notice that this <srcript> syntax is used in Vue components.

<script setup>
import HelloWorld from './components/HelloWorld.vue'
// 这个模板使用的是Vue3实验性`<script setup>` SFCs

You may be wondering, "What the hell is this? Is this the Options API? Or the Composition API? Where is the setup

<script setup> type is a recommendation in Vue's Git RFC. To be clear, this is not meant to completely replace any current writing. Its purpose is to provide developers with a more concise syntax to write their individual file components.

In this article, we carefully study its working principle and some useful methods.

script setup

In <script setup> , we don't need to declare the export default and setup methods. This way of writing will automatically expose all top-level variable declarations to the template.

In the Composition API, we are used to creating a setup method, and then returning what we want to expose, as shown below:

<script>
import { ref, computed } from 'vue'
export default {
   setup () {
      const a = ref(3)
      const b = computed(() => a.value + 2)
      
      const changeA = () => { a.value = 4 }
      return { a, b, changeA } // have to return everything! 
   }
}
</script>

If we use <script setup> syntax, we can use the following code to achieve the same function as above:


<script setup>
import { ref, computed } from 'vue'
// all of these are automatically bound to the template
const a = ref(3)
const b = computed(() => a.value + 2)
      
const changeA = () => { a.value = 4 } 
</script>

Not only data, calculation properties and methods, even instructions and components can also be automatically obtained template

<template>
     <component-b />
</template>
<script setup>
import ComponentB from './components/ComponentB.vue' // really that's it!
</script>

This is magic.

So, what is the point of this?

To make a long story short, this syntax makes single file components simpler.

In the original words of the RFC, "The main goal of the proposal is to reduce the verbosity of Composition API SFC by directly exposing the context of <script setup>

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

More advanced usage of <script setup>

Now that we know what <script setup> is and why it is useful, let's take a look at some of its more advanced features.

Access props, emit events, etc.

First, you may want to know how to perform standard Vue operations, such as:

  • Access props
  • How to emit custom events
  • Access context object

In the Composition API, these are placed in the parameters of setup

setup (props, context) {
    // context has attrs, slots, and emit
}

However, in the script setup syntax, we can access these same options by importing the corresponding API three times from Vue.

  • defineProps-As the name suggests, it allows us to define props for the component
  • defineEmits-define the events that the component can emit
  • useContext-can access the slots and properties of the component
<template>
 <button @click="$emit('change')"> Click Me </button>
</template>
<script setup>
  import { defineProps, defineEmit, useContext } from 'vue'

  const props = defineProps({
    foo: String,
  })
  const emit = defineEmit(['change', 'delete'])

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

Through these three kinds of imports, we can get the functions that are used in traditional setting methods.

Create an asynchronous setup method

Another cool feature of the script setup setup is very easy to create asynchronous 060b42e12bfa95.

This is useful for loading APIs when creating components and even binding code to <suspense> functions.

We have to do is let our setup functions are asynchronous, in our script setup use a top-of await .

For example, if we are using Fetch API, we can use await

<script setup>   
   const post = await fetch(`/api/pics`).then((a) => a.json())
</script>

So the setup() function will be asynchronous.

Use <script setup> and a normal <script>

<script setup> creates its own script scope for its top-level binding. But in some cases, code must be executed within the scope of the module.

The 2 specific examples in this RFC are:

  • Declaring named exports
  • Create global side effects that are executed only once

This can be done by adding a normal <script> block next to the script setup, as shown below.

<script>
  performGlobalSideEffect()

  // this can be imported as `import { named } from './*.vue'`
  export const named = 1
</script>

<script setup>
  // code here
</script>

to sum up

Currently, this script setut is optional, so if you want to try it, just add setup script tag.

To learn more about script setup more information, please here , links to the full RFC and its motives, the exact syntax and more technology.


code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://learvue.co/2021/05/explaining-the-ne-script-setup-type-in-vue-3-major-takeaways-from-the-rfc/

communicate with

If you have dreams and dry goods, search on [Moving to the World] attention to the wisdom of brushing the dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68.1k 声望105k 粉丝