Introduction
With the introduction of Vue 3, a new component option and a new advised pattern were added to the framework for creating apps. You may get top-level bindings using this magical script setup> method of implementing the logics without having to go through the extra trouble of declaring an export default and a setup().
Why <script setup> ?
Leaner codebase, faster development, readable and easier coding experience by reducing component choices into a single block. With each of these features, Reactivity makes things more simpler.
Using Props with <script setup>
Using the <script setup> , a function called defineProps() is utilized. This function is a compiler macro, so there is no need to import it.
<template>
<div>
<p>Received Prop: {{ propValue }}</p>
</div>
</template>
Options API :
<script>
export default {
props: {
propValue: String
}
};
</script>
Composition API :
<script setup>
const props = defineProps({
propValue: String
});
</script>
Using Methods with <script setup>
Methods will be specified as consts and available in your template just like they were in the Options API, since methods are no longer considered objects.
Options API :
<template>
<div>
<button @click="incrementCounter">Increment</button>
<p>Counter: {{ counter }}</p>
</div>
</template>
<script>
export default {
data() {
return {
counter: 0
};
},
methods: {
incrementCounter() {
this.counter++;
}
}
};
</script>
Composition API :
<template>
<div>
<button @click="incrementCounter()">Increment</button>
<p>Counter: {{ counter }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const counter = ref(0);
const incrementCounter = () => {
counter.value++;
};
</script>
Using Computed with <script setup>
Computed in Composition API operate as reactive data variables. They perform the role of a function, returning calculated values depending on reactive dependencies.
Options API :
<template>
<div>
<button @click="incrementCounter">Increment</button>
<p>Counter: {{ counter }}</p>
<p>Double Counter: {{ doubleCounter }}</p>
</div>
</template>
<script>
export default {
data() {
return {
counter: 0
};
},
computed: {
doubleCounter() {
return this.counter * 2;
}
},
methods: {
incrementCounter() {
this.counter++;
}
}
};
</script>
Composition API :
<template>
<div>
<button @click="incrementCounter">Increment</button>
<p>Counter: {{ counter }}</p>
<p>Double Counter: {{ doubleCounter }}</p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const counter = ref(0);
const doubleCounter = computed(() => {
return counter.value * 2;
});
</script>
`
Top comments (0)