In this tutorial, we will see how to use number variable in Vue 3 with TypeScript.
1. Vue 3 with TypeScript define a number variable.
Vue
<template>
<div>
<p>The value of the number is: {{ count }}</p>
</div>
</template>
<script setup lang="ts">
let count: number = 1
</script>
2. If you want use string and number then you can use |.
Vue
<template>
<div>
<p>The value of the number is: {{ count }}</p>
</div>
</template>
<script setup lang="ts">
let count: number | string = 1
</script>
3. Vue 3 options api with TypeScript define a number variable.
Vue
<template>
<div>
<p>The value of the first number is: {{ number1 }}</p>
<p>The value of the second number is: {{ number2 }}</p>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
data() {
return {
number1: 1 as number,
number2: 2 as number
}
}
})
</script>
4. Vue 3 with TypeScript define a number variable using ref.
Vue
<template>
<div>
<p>The value of the number is: {{ count }}</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const count = ref<number>(1)
</script>
5. Create simple counter app with Vue 3 with TypeScript.
Vue
<template>
<div class="custom-container">
<div>
<p>The value of the counter is: {{ counter }}</p>
<button @click="increment">Increment</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const counter = ref<number>(0)
const increment = () => {
counter.value++
}
</script>
<style scoped>
.custom-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
</style>
6. . Use number in function with Vue 3 with TypeScript.
Vue
<template>
<div>
<p>The value of x + y is: {{ total() }}</p>
</div>
</template>
<script setup lang="ts">
function total(): number {
const x: number = 5
const y: number = 10
const result: number = x + y
return result
}
</script>
Javed sheikh
Hello there! I’m Javed Sheikh, a frontend developer with a passion for crafting seamless user experiences. With expertise in JavaScript frameworks like Vue.js, Svelte, and React, I bring creativity and innovation to every project I undertake. From building dynamic web applications to optimizing user interfaces,