Vue3.0 syntax sugar script setup

Writing in the front

As we move into VUe3.0 our VUE code template format also changes and maybe you’ll see code like this

<template>
  <div>
​
  </div>
</template>
​
<script lang="ts">
import { defineComponent } from 'vue'
​
export default defineComponent({
  setup () {
    
​
    return {}
  }
})
</script>
​
<style scoped>
​
</style>
Copy the code

But every time we have to import defineComponent and then export it makes us really upset. The writing method of VUe3.0 seems to become a lot more complicated

So it came

<template>
  <div>
​
  </div>
</template>
​
<script setup lang="ts">
​
</script>
​
<style scoped>
​
</style>
Copy the code

Doesn’t it feel a lot better? Of course, that’s just a comparison. How do we use it

  1. Basic usage

    Under Conponents, create a new msg.vue

    <template>
      <div>
        {{ msg }}
      </div>
    </template>
    ​
    <script setup>
      let msg = "hello!"
    </script>
    Copy the code

    The second thing we do is reference it in the parent component

    <template> <img Alt ="Vue logo" SRC ="./assets/logo.png" /> <HelloWorld MSG ="Hello Vue 3.0 + Vite" </template> <script setup> import HelloWorld from './components/HelloWorld.vue' import msg from "./components/msg.vue" </script>Copy the code

    You can see that in the parent component, you can import directly and you don’t need to do anything, even in VUe2.0

    components:{
       msg
    }
    Copy the code

    You no longer have to worry about component references not being attached to components

  2. Props and emit

    Because the idea in 3.0 was to import before use and not to load all the apis at once, it is the same with props and emit

    You need to import defineProps and defineEmit first. This is introduced because of the script setup tag, which is equivalent to props and emit

    <template> <div> {{MSG}} < button@click ="onClick" </button> </div> </template> <script setup> import { defineProps, defineEmit } from "vue"; // props emit let props = defineProps({ msg: String, }); console.log(props); let emit = defineEmit(["click"]); const onClick = () => { emit("click"); Console. log("click..." ); }; </script>Copy the code

    In the app, vue

    <template> <img Alt ="Vue logo" SRC ="./assets/logo.png" /> <HelloWorld MSG ="Hello Vue 3.0 + Vite" /> < MSG MSG =" Good weather" @click="onClick"></msg> </template> <script setup> import HelloWorld from './components/HelloWorld.vue' import msg from "./components/msg.vue" </script>Copy the code

    B: well… Sweet y

    New syntax sugar-script setup for Vue3.0

    If there is infringement trouble contact the author to delete

    \