Home  >  Article  >  Web Front-end  >  What is the difference between

1. Basic syntax

How to write the setup function

<script>
import { ref } from &#39;vue&#39;
export default {
  setup () {
    const num = ref(1);
    return { num }
  }
}
</script>

The variables and functions defined in the setup function need to be returned, otherwise they cannot be used normally.

How to write syntax sugar in <script setup></script>

<script setup>
    import { ref } from &#39;vue&#39;
    const num = ref(1)
</script>

Variables and functions defined in syntax sugar in

3. Register component

setup function

<script>
import Hello from &#39;@/components/HelloWorld&#39;
export default {
  components: {
    Hello
  }
}
</script>

<script setup>
import Hello from &#39;@/components/HelloWorld&#39;
</script>

No need to register in component, you can use it directly.

4. Use custom instructions

setup function

<template>
    <h2 v-onceClick>使用了setup函数</h2>
</template>
<script>
export default {
  directives: {
    onceClick: {
      mounted (el, binding, vnode) {
        console.log(el)
      }
    }
  },
}
</script>

<template>
    <h2 v-my-Directive>使用了script setup</h2>
</template>
<script setup>
const vMyDirective = {
  beforeMount: (el) => {
    console.log(el)
  }
}
</script>

Globally registered custom instructions will work normally. Local custom instructions do not need to be explicitly registered in <script setup></script>, but they must follow the naming convention of vNameOfDirective

##5. Passing from father to son Data communication

<Com :num="100"></Com>

setup function

<script>
export default {
  props: {
    num: {
      type: Number,
      default: 1
    }
  },
  setup (props) {
    console.log(props)
  }
}
</script>

<script setup>Syntactic sugar

<script setup>
import { defineProps } from &#39;vue&#39;
const props = defineProps({
  num: {
    type: Number,
    default: 1
  }
})
</script>

6. Data communication from child to parent

setup function

<script>
export default {
  setup (props, context) {
    const sendNum = () => {
      context.emit(&#39;sendNum&#39;, 200)
    }
    return { sendNum }
  }
}
</script>

<script setup>Syntax sugar

<script setup>
import { defineProps, defineEmits } from &#39;vue&#39;
const emit = defineEmits([&#39;submit&#39;])
const sendNum = () => {
  emit(&#39;submit&#39;, 1000)
}
</script>

defineProps and defineEmits are compiler macros that can only be used in