script setup lang ts
Code

Script setup Vue 3 – ❮Script lang=”ts” setup❯

Script setup <Script lang=”ts” setup> is something i really appreciate after migrating from vue 2. It is a part of the new Script Setup feature introduced in Vue 3. It replaces the traditional <script> block and provides a more concise and focused way to write components. The purpose of <script setup> is to simplify component code by removing unnecessary boilerplate and reducing redundancy.

What Does It Do?

The code inside <script setup> is compiled as the content of the component’s setup() function. You can remember it from vue 2 for both, composition and options api.
Unlike the normal <script> block, which executed only once when the component is first imported, code inside <script setup> runs every time an instance of the component is created.


Top-level bindings (such as variables, functions, and imports) defined within <script setup> are exposed to the template, making them accessible for use in the component’s template. Think of it as automated return {} block.

TypeScript Integration

In <Script lang="ts" setup>, the lang=”ts” attribute indicates that TypeScript is being used within the component. When lang=”ts” is present, all template expressions (such as props, data, and computed properties) enjoy stricter type checking. It might sometimes go sideways but pretty much works well. Help a lot also. Just remember to actualy use the types in typescript 🙂 ( Yes i saw methods returning either a boolean, either a string or even undefined, all at the same time ).
Strict typing, like in scala or java, helps catch type-related errors early during development, improving code quality and maintainability. Of course there is always an trade off for speed of coding.

Example usage :

<template>
  <div>{{ message }}</div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';

  // Define reactive message
  const message = ref('Hello, world!');

  // Define a function to change the reactive  property
  function updateMessage(newMessage: string) {
    message.value = newMessage;
  }
</script>

Accessing Component Internals:

When using <script setup>, the code is transformed in a way that hides component internals by default.
To make specific methods or properties accessible externally, you can use the defineExpose function.
For example, if you want to expose a method called myMethod, you would do:
defineExpose({
myMethod
});

Now myMethod can be accessed from outside the component. Might be helpfull while testing but i don`t really see the point. All should be stored in pinia store anyway for the sake of separation of concerns.

Summary

In summary, <script lang=”ts” setup> simplifies component code, provides TypeScript integration, and allows you to expose specific methods or properties. Enhances developer productivity and code quality in Vue 3 applications.

Quoting professor Slughorn from HP

” Use it well… „

Piotr Kowalski