Now that we have a common base whether you use the Vue CLI locally or CodeSandbox, we can start building our app.
Given the premise of the introduction, we’ll start with 3 components: AddProduct, ProductsList and SingleProduct, which will provide
- the add product form
- the products list
- the single product view
Those components will all be added to the navigation on top of the page, along with “Home” and “About”.
let’s start by adding them, with a minimal boilerplate to just see them working as part of the router:
src/views/AddProduct.vue
<template>
<div class="">
<h1>Add Product</h1>
</div>
</template>
src/views/SingleProduct.vue
<template>
<div class="">
<h1>Single Product</h1>
</div>
</template>
src/views/ProductsList.vue
<template>
<div class="">
<h1>Products List</h1>
</div>
</template>
Next, import those in src/router.js
:
import AddProduct from './views/AddProduct.vue'
import ProductsList from './views/ProductsList.vue'
import SingleProduct from './views/SingleProduct.vue'
and add them to the Router
object initialization:
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
},
{
path: '/products',
name: 'products',
component: ProductsList
},
{
path: '/product/:slug',
name: 'product',
component: SingleProduct
},
{
path: '/add-product',
name: 'add-product',
component: AddProduct
}
]
})
Notice how we add a specific path to each component, and the Product component accepts a dynamic path /product/:slug
. There will be multiple pages on the site that match the Product component, one for each different product.
Next up, we add the links in the App component template:
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/products">Products</router-link> |
<router-link to="/add-product">Add Product</router-link>
</div>
<router-view/>
</div>
</template>
And the final result should be this:
The code at this point is at https://codesandbox.io/s/zzxmm452k3