vue router Quick Start to Learning
- 2021-07-24 09:55:17
- OfStack
vue-router Quick Start
Configure routing
$ npm install vue-router --save
routes.js
import Home from './pages/Home.vue'
import Gifs from './pages/Gifs.vue'
import User from './pages/User.vue'
export const routes = [
{ path: '', component: Home },
{ path: '/gifs', component: Gifs },
{ path: '/user/:id', component: User }
// Specify the route and the corresponding component to render
//404 Adj. path It should be '*', It should be placed at the end, and it will not match until all the previous ones do not match 404 Page
//this.$route.params.id You can get it from the route id Data
]
main.js
import VueRouter from 'vue-router'
import { routes } from './routes'
Vue.use(VueRouter)
// Route initialization
const router = new VueRouter({
routes
})
// Injecting routes into the root component
new Vue({
el: '#app',
...
router,
render: h => h(App)
})
App.vue
<template>
<div class="app">
<router-view></router-view>
</div>
</template>
Mark the location of component rendering in the template
Meaning of #
Before #, the request sent to the server to return the html file is indicated, while after #, the request sent to the local js to seek resolution is indicated
Dynamic binding of routing parameters
Use watch
watch: {
'$route'(to,from) {
//to The current route, from Upper 1 Routes
this.id = to.params.id
}
}
Data transfer of routing
<router-link :to="{ name: 'userEdit', params: { id: $route.params.id }, query: { locale: 'en', list: 2 } }"></router-link>
Passing query parameters can reach the address bar/? locale = en
&
list=2
Accessed by $route. query. Key name
Named view
router-view can specify the position of component rendering by configuring the name name, which increases the reusability of components. For example, it is divided into header main hero footer to load different components at different positions in one view
Lazy loading of components
We only need to load the components we need to present to the user, and other components that do not need to be loaded in the first time can be loaded asynchronously using webpack, and only when needed will a request be issued to load another component
routes.js
const User = resolve => {
require.ensure(['./components/user/User.vue'], () => {
resolve(require('./components/user/User.vue'))
}, 'GroupName')
}
//webpack Asynchronous loading, through the group name, will be performed at the same time 1 Packaging and loading of loaded components