In Building a Store with Vue – Part Two we will discuss setting up a Single Page Application for our Vue based shop. This means there will be one single url (endpoint) with multiple views.
Vue Router
To work with routes and thereby creating views or pages using Vue instead of Laravel routes we have to install Vue Routes. This we do using:
npm install --save vue-router
In our case Vue Router was only updated as we installed it when we did a
vue init webpack
In src/routes/index.js you can see:
import Vue from 'vue'; import Router from 'vue-router'; import HelloWorld from '@/components/HelloWorld'; Vue.use(Router); export default new Router({ routes: [ { path:'/', name:'HelloWorld', component:HelloWorld, }, ], });
this shows you the router plugin is imported and that is is used by our application. You also see that an array is added in which you can add your routes. And all this is done on the fly.
Routes Needed
Routes that we will be needing to create our basic Vue Store are:
- home
- admin
- cart
More of course are needed to create a full fledged shop like a detailed admin dashboard to create basic product categories, product tags, view orders, settings and much more, but let’s just stick to this for the purposes of this Vue SPA Store.
Each route will be needing its own component.
Home Vue Component
For the homepage create src/components/Home.vue and add:
<!-- ./src/components/Home.vue --> <template> <div> <div class="title"> <h1>{{msg}}</h1> </div> </div> </template>
This followed by the actual message:
export default { name:'home', data() { return { msg:'Welcome to Your Shop App', }; }, };
Home Route
Then add the following code to your routes array in ./src/router/index.js
{ path: '/', name: 'Home', component: Home, }
As you can see we need to add:
- path
- route name
- component name
This was added as a replacement of the previous route:
{ path:'/', name:'HelloWorld', component:HelloWorld, },
Also import the component by adding:
import Home from '@/components/Home';
at the top replacing HelloWorld.vue.
Final Home Page Code
Once you have created your home route and component you should have a basic homepage up and running. You should now have Home.vue with:
<!-- ./src/components/Home.vue --> <template> <div> <div class="title"> <h1>{{msg}}</h1> </div> </div> </template> <script> export default { name:'home', data() { return { msg:'Welcome to Your Shop App', }; }, }; </script>
and main.js with:
// ./src/router/index.js import Vue from 'vue'; import Router from 'vue-router'; import Home from '@/components/Home'; Vue.use(Router); export default new Router({ routes: [ { path:'/', name:'Home', component:Home, }, ], });
This main.js has the top part with code generated by Vue CLI and the new path added by us. Running
npm run dev
you should now see: