Padawan Learner
Padawan Learner

Reputation: 55

Switching Between Components in a Vue App

I'm building a single-file-based Vue application from a template generated with the Vue UI tool.

I understand how a .vue file defines the styling/structure/behavior of a component, how smaller components can be composed into bigger components, and how the top-level "App" component mounts everything to an HTML Div.

As the user progresses through the app, though -- say from a login screen to a master screen to a detail screen -- what's the accepted approach to switching out the current screen-level component?

Ty in advance.

--The Vuebie

Upvotes: 1

Views: 3136

Answers (1)

Oamar Kanji
Oamar Kanji

Reputation: 2224

This is quite an open ended question so ill just show you what I have done in my own projects. I split my components directory into two directories; 'pages' and 'common'. (Ignore the 'firebase' directory is it beyond the scope of this question).

enter image description here

The common directory holds components that may be used in a page or re used in several different pages.

enter image description here

For example the 'account form' is used in my 'Edit Account page' and the category bar is used in several of my pages.

The pages directory holds components that are technically no different from my common components but they represent full pages on my website. A page component may contain several common components.

enter image description here

Now the biggest distinction between common and pages is in the router. I route different paths relative to the main url (that is probably not the technically correct description but hopefully you get the point) to each of the pages. Here is my index.js file from my router directory:

enter image description here enter image description here

As you can see, I have a route pointing to each one of my pages. You can " switch out the current screen-level component" (as you put it) by using router-link tag's to navigate between different page components. These are clickable urls that your client can use, they can also be wrapped in buttons and such.

For example, this router link navigates to my home page, the component name is 'Helloworld'. See its corresponding reference in my router's index.js and in the pages directory so you can connect it all in your head.

<router-link class="nav-item nav-word" :to="{ name: 'HelloWorld' }">

Finally, I will talk a bit about the App.vue file. The App.vue acts like a base component as it contains the 'router view' tag within it's template:

<router-view/>

This means that every page that you route will be placed in the position of the 'router view tag'. I.e this tag will be replaced with the page. It is common practise to surround this tag with html code that you would like to be shown in each page. For example I have my router view tag between my nav bar and footer. So that the nav bar and footer will show on each page.

Upvotes: 6

Related Questions