Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Before we simply learned the initial use of VUe-Router, and to achieve a specific study today Vue project small actual practice of page switching: routing VUe-Router
Vue-router Indicates the use of front-end routes
The difference between the front and back end routes
Back-end routes return different content based on different urls
Front-end routes switch different components based on different hash values
Hash mode code implementation
Listen for hashchange changes for path processing
<html>
<head>
<meta charset="utf-8" />
<title>Parsing the hash mode of front-end routes</title>
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.js"></script>
</head>
<body>
<a href="#/page-one">page-one</a>
<a href="#/page-two">page-two</a>
<a href="#/page-three">page-three</a>
<div id="box"></div>
</body>
<script>
const routes = [
{
path: '/page-one'.component: './template/one.html'
},
{
path: '/page-two'.component: './template/two.html'
},
{
path: '/page-three'.component: './template/three.html'},]let hash = location.hash // Get the hash value
if(! hash) { location.hash ='#/one' // The default hash value is '#/one'
}
hash = location.hash.replace(The '#'.' ') // Remove the '#' from the hash
let cache = {} // used as a cache
window.addEventListener('hashchange'.() = > {
hash = location.hash.replace(The '#'.' ')
routes.forEach(item= > {
if(item.path === hash) {
if(cache[hash]) { // If there are accessed objects in the cache, use the objects in the cache
$('#box').html(cache[hash])
}
} else {
$.ajax(item.component).then(res= >{$('#box').html(res)
cache[hash] = res
})
}
})
})
</script>
</html>
Copy the code
How to use routes and redirect routes and 404 pages
Child routing uses children
- Exact matches only when the style is applied
path
Routing and the cords
-
this.$route.params.id]
-
props
-
<router-link :to={'name': name :params:{key-value pair.... }}
import axios from "axios"
Vue.prototype.axios=axios;
Copy the code
Use it once in the entry file for other components
this.$http.get
Copy the code
Components are not uninstalled when routing parameters are switched
However, when a routing component is switched, the component is unloaded
const routes: [
{
path: 'pageone'.component: './template/PageOne.html'}, {path: 'pageone'.component: './template/PageTwo.html'}, {path: 'pageone'.component: './template/PageThree.html'],},Copy the code
Routing and the cords
This.$route.params.id props
The third kind of