I am new to vue but scince i am fresh starting i decied to go straight up to TS and Setup tag because seems like the newest and best way to write vue js components.
Anyways i am now looking at this framework and more specific i'm into this example:
import { IonPage, onIonViewWillEnter, onIonViewDidEnter, onIonViewWillLeave, onIonViewDidLeave } from '@ionic/vue';
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Home',
components: {
IonPage,
},
setup() {
onIonViewDidEnter(() => {
console.log('Home page did enter');
});
... the other hooks ...
},
});
And my question come from this block:
name: 'Home',
components: {
IonPage,
},
since i only worked with options api and setup tag i an not sure What does it imply to put an object in the components object and how could i acomplish the same objective with setup tag.
My objective is to make sure i am doing what this Note in the guide warns me about:
Note Pages in your app need to be using the IonPage component in order for lifecycle methods and hooks to fire properly.
CodePudding user response:
In <script setup>
syntax, Home.vue would look like this:
<script setup lang="ts">
import { IonPage, onIonViewDidEnter, ...other hooks used here... } from '@ionic/vue';
onIonViewDidEnter(() => {
console.log('Home page did enter');
});
...other hooks used here...
</script>
The note you quoted draws attention to the template of any page/view contents needing to be wrapped in a <ion-page></ion-page>
wrapper for the layout to function as intended, like in their examples.
Generic example:
<template>
<ion-page>
<ion-header>
<ion-toolbar>
<ion-title>Some title</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
some content...
</ion-content>
</ion-page>
</template>
For the above layout, you'd need to import all used components:
import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent } from '@ionic/vue'
With <script setup>
you don't need to declare them as local components, <script setup>
detects them and does it for you, behind the scenes. They're available for usage inside the <template>
once imported.
The component name
is also inferred by <script setup>
from the name of the file. In the above case, it would be Home
.
To sum up: behind the scenes, <script setup>
takes its contents and wraps it in a
export default defineComponent({
name: // infer from file name,
components: {
// list all imported vue components
},
setup() {
// actual contents of `<script setup>`
}
})
For this to be possible, some helpers were added (defineEmits
, defineProps
), which allow declaring those parts of Options API inside the setup()
function.
Most notably, in this syntax setup()
no longer needs a return
value. All variables declared or imported inside it are made available to <template>
.
Important: <script setup>
is a useful tool, designed to reduce boilerplate in the majority of cases, not to replace defineComponent()
completely. Read more about it in the docs.