diceline-chartmagnifierquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

Script setup syntactic sugar for the Composition API in SFCs

Problem: When using the Composition API, we need to return all (reactive) variables from the setup() method in order to use them in the template section. This can make components huge, harder to read and maintain and also cause unwanted bugs if we forget to return any variables used in the template. More than that, we can use variables only by accessing their "value" property.

This is the basic structure of a component that we want to improve:

<script>
//Long list of imports 

import Child1 from 'child1-location';
import Child2 from 'child2-location';
import { ref } from 'vue';

export default defineComponent({
  name: 'CustomComponent',
  components: { Child1, Child2 },
		
  setup() {
	const variable1 = ref(1);
	const variable2 = ref(2);
	//...
	const variable100 = ref(100);

	//altering variables
	variable1.value = 'new value for variable1';

	return {
		variable1,
		variable2,
		.
		.
		.
		variable100,
	}
  }
});
</script>

<template>
	<Child1 />
	<Child2 />
	{{ variable1 }}
	...
	{{ variable100 }}
</template>

Solution: The structure and performance of this component can be improved by using the Script Setup syntactic sugar. 
The Script Setup is a compile-time syntactic sugar that is recommended to be used in SFCs with the Composition API. Let's rewrite the component from above using the Script Setup:

<script setup> 
	
import Child1 from 'child1-location';
import Child2 from 'child2-location';
import { ref } from 'vue';
	
const variable1 = ref(1);
const variable2 = ref(2);
//...
const variable100 = ref(100);

variable1 = 'new value for variable1';
</script>

<template>
        <Child1 />
	<Child2 />
	{{ variable1 }}
	...
	{{ variable100 }}
</template>

Important differences and advantages: 



  1. We don't need to return any variables from our script in order to use them in the template, reducing the number of lines and increasing readability and operability
  2. We don't need to use .value to access and modify reactive variable values
  3. We can directly use imported Child Components in our template without registering them
  4. Better runtime performance due to the behind the hood implementation of the template (as a render function without an intermediate proxy)
  5. TypeScript support for defining props and emitted events (will be described in a future TIL)