SoFunction
Updated on 2025-04-05

Detailed explanation of the setup syntax sugar instance updated by vue3

Preface

Vue3 recently updated a setup syntax sugar. I saw it in the past two days. The food is very sweet when used. I posted a special post to record it.

Syntactic sugar usage:

// Add `setup` attribute to the `<script>` code block// The code inside will be compiled into the contents of the component `setup()` function// It's that simple and clear&lt;script setup&gt;

&lt;/script&gt;

The experience brought by grammatical sugar

1. Automatic component registration

// No need to use components, register as soon as it is introduced, is there any takeoff?&lt;script setup&gt;
    import MyComponent from './'
&lt;/script&gt;

&lt;template&gt;
  &lt;MyComponent /&gt;
&lt;/template&gt;

2. No need to return properties and methods

// When using `<script setup>`, any bindings at the top level declared by `<script setup>`// (including variables, function declarations, and content introduced by import) can be used directly in templates
import { ref } from 'vue'
&lt;script setup&gt;
// Variablelet msg = ref('Hello!')

// Functionfunction log() {
   = "World!";
  (msg)
}
&lt;/script&gt;

&lt;template&gt;
  &lt;div @click="log"&gt;{{ msg }}&lt;/div&gt;
&lt;/template&gt;

3. Automatically define the file name as the name attribute of the component

API provided by syntax sugar

Props and emits must be declared in <script setup>                                                                                                                                                                                                                                                        �

1、defineProps

<script setup>
const props = defineProps({
  foo: String
})
</script>

2、defineEmits

<script setup>
const emit = defineEmits(['change', 'delete'])
// emit('change', '1111')
</script>

3、defineExpose

If the child component instance is obtained in the parent component using the method of ref='xxx', and the child component uses <script setup>, the data of the child component needs to be exported in the form of defineExpose, otherwise its properties will not be exposed.

<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
  a,
  b
})
</script>

<script setup> can be used with ordinary <script>

&lt;script&gt;
// Normal <script>, executed in the module scope (execute only once)// Declare additional options, such as custom component namesexport default {
  name: 'Component 1'
}
&lt;/script&gt;

&lt;script setup&gt;
// code
&lt;/script&gt;

Summarize

This is the end of this article about the update of vue3 setup syntax sugar. For more related content of vue3 setup syntax sugar, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!