Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Today we are going to learn the page switch of Vue project
Vue-router Indicates the front-end route
Front-end routing switches between different components based on different hash values, that is, displays different page contents
< Step 1 Install route >
cnpm i vue-router --save
Copy the code
< Step 2 is introduced in main.js >
import VueRouter from'the vue - the router'Copy the code
< Step 3 use >
Vue.use(VueRouter)
Copy the code
< Step 4 instantiate >
var router = new VueRouter()
Copy the code
< Step 5 Register the router in the root instance
// main.js
import Vue from 'vue'
import VueRouter from 'vue-router' // Import routes into the project
Vue.use(VueRouter)
var router = new VueRouter()
new Vue({
el: '#app',
router, // Register the router
})
Copy the code
< Step 6 write in App >
See the following code should have a page! Heh heh, please imagine:
<router-link to=The path "" "" /> <router-view />
Copy the code
// app.vue
<template>
<div id="app">
<my-component></my-component>
<router-link :to="/pageone">This is the first page<router-link>
<router-link :to="/pagetwo">This is the second page<router-link>
<router-link :to="/pagethree">This is the third page<router-link>
<router-view/> <! -- container for the component to switch routes -->
</div>
</template>
Copy the code
Split routing module
Make the move, split the routing module into the Router folder, create index.js,
You can also separate routes: / SRC /router/routes.js and index.js
// src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router' // Import routes into the project
import PageOne from '@/components/PageOne' // Introduce the corresponding page component in the project
import PageTwo from '@/components/PageTwo' // Introduce the corresponding page component in the project
import PageThree from '@/components/PageThree' // Introduce the corresponding page component in the project
Vue.use(VueRouter)
var router = new VueRouter({
routes: [{path: 'pageone'.component: PageOne,
},
{
path: 'pageone'.component: PageTwo,
},
{
path: 'pageone'.component: PageThree,
},
],
})
export default router
Copy the code
Just import/register in main.js.
summary
Install import registration for use
cnpm i vue-router --save
Copy the code
Routing principles:
-
Routing works by switching components based on hash value changes
localtion.hash
Get the hash valuehashchange
Switch components
-
Default hash mode of the route
- The history mode