Vue 3 Script Setup Cheat Sheet
Everything declared inside
script setup
is available in the template.
Methods
<script setup>
function getParam(param) {
return param;
}
</script>
<template>
</template>
Reactive Data Declaration
<script setup>
import { ref, reactive } from 'vue';
const enabled = ref(true);
const object = reactive({ variable: false });
</script>
Component Declaration
<script setup>
import { defineAsyncComponent } from 'vue';
import TheComponent from './components/TheComponent.vue';
const AsyncComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
);
</script>
Computed Value
<script setup>
import { computed } from 'vue';
const count = 0;
const isEmpty = computed(() => {
return count === 0;
});
</script>
Watcher
<script setup>
import { watch, ref } from 'vue';
const counter = ref(0);
watch(counter, () => {
console.log('Counter value changed');
});
</script>
Lifecycle Hooks
<script setup>
import { onMounted } from 'vue';
console.log('Equivalent to created hook');
onMounted(() => {
console.log('Mounted hook called');
});
</script>
Define Emits
<script setup>
const emit = defineEmits(['event-name']);
function emitEvent() {
emit('event-name');
}
</script>
Define Props
<script setup>
const props = defineProps({
elements: Array,
counter: {
type: Number,
default: 0,
},
});
</script>