<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
data() {
// This data will be available in your template
return { name: 'Erik' }
}
})
</script>
Fancier way using ES6 to return an object
export default defineComponent({
data: () => ({
name: 'Erik'
})
})
export default defineComponent({
setup() {
let name = 'Erik'
return {name}
}
})
<script lang="ts" setup>
let name = 'Erik'
</script>
NOTE: In vue 2, we import comonents etc. outside of script tag
<script lang="ts" setup>
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<HelloWorld/>
</template>
<script lang="ts" setup>
const props = defineProps({ name: String })
</script>
<template>
<h1>Name: {{ props.name }}</h1>
</template>
<script lang="ts" setup>
const props = withDefaults(defineProps<{name ?: string}>(), { // ? means it could be nullable
name: 'Steve' // Default values goes here ...
})
</script>
NOTE: No need to import defineProps()
or withDefaults()
Or we can use interfaces for type declations
<script lang="ts" setup>
interface props {
name ?: string
}
const props = withDefaults(defineProps<props>(), {
name: 'Steve'
})
</script>
Child Component:
<template>
<button @click="clicked">Click Here!</button>
</template>
<script lang="ts" setup>
const emits = defineEmits(['pressed'])
function clicked() {
emits('pressed', 'You are awesome') // second argument is the payload
}
</script>
Parent Component:
<template>
<HelloWorld @pressed="pressed"/>
</template>
<script lang="ts" setup>
function pressed(info: string) {
alert('pressed ' + info)
}
</script>
<script lang="ts" setup>
import { ref } from "vue";
let pokemon = ref(null) as any; // To get rid of vs code typescript warnings
async function pressed() {
const info = await fetch("https://pokeapi.co/api/v2/pokemon/ditto");
const json = await info.json();
pokemon.value = json;
}
</script>
We need to use
.value
to access ref values inside script tag (not template)
You don't have to necessarily put them into props. and if you don't it will add to outer tag that surround component.
Parent Component
<HelloWorld class="green" />
HelloWorld.vue
<template>
<h1>Hello</h1>
<h2>from</h2>
<h3>World</h3>
</template>
It doesn't work and show warnings because we don't have single root element.
We can slove it by wrapping them with <div>
<template>
<div> // It renders <div class="green">...</div>
<h1>Hello</h1>
<h2>from</h2>
<h3>World</h3>
</div>
</template>
We can have multiple script tags
<script lang="ts">
export default {
inheritAttrs: false
};
</script>
But how do put it where I wanted to be?
<script lang="ts" setup>
import { useAttrs } from "vue";
const attrs = useAttrs();
</script>
<template>
<h1 v-bind="attrs">Hello</h1>
</template>
or even simpler just use $attrs
in template