DEV Community

Cover image for How to use PortalVue
David
David

Posted on

How to use PortalVue

There some many times in the development of an app that it's required to change the behaviour of a component. Nowadays, frameworks provide some many ways to overlap those components and one it's surprised me was a small package that will be included in VueJS 3, and today is named portals.

Play to open a portal

Yes, if you have a little gamer culture you hear about portals and it reminds you about Valve. We can say that this works that way.

PortalVue is an actual VueJS 2 plugin that let us send some components from a template to another template.

How to use portals

To install PortalVue, we only have to write on our bash:

yarn add portal-vue
Enter fullscreen mode Exit fullscreen mode

Then, we must add the following lines to our main.js

import PortalVue from 'portal-vue'
Vue.use(PortalVue)
Enter fullscreen mode Exit fullscreen mode

How to send components through portals

Ok, in our project we had troubles. We need to override the AppBar depending on the view. We are coding an Ionic app and we didn't want to use so many code for that.

In our project layout view, we set up our destination portal. This is the portal used to show the content.

<PortalTarget name="header" tag="ion-header"></PortalTarget>
Enter fullscreen mode Exit fullscreen mode

We are setting a name what is the reference to send the content in the other side of the portal.

When we need to show an AppBar, we only have to define it in the view and customize it.

<Portal to="header">
    <ion-toolbar></ion-toolbar>
</Portal>
Enter fullscreen mode Exit fullscreen mode

How you can see, it is very simple to use. According to the author, it will be available in Vue.js 3 as core functionality and renamed as <Teleport />

I hope it is useful 😁

Top comments (0)