SPA(Single Page Application): a single page application with only one complete page; When it loads a page, it does not load the entire page, but only updates the contents of a specified container. One of the core aspects of a single page application (SPA) is updating a view without rerequesting the page; Vue-router implements single-page front-end routing. This article was contributed to Github.
router
- $route is a route information object, including
Path, Params, Hash, Query, fullPath, matched name
And other routing parameters. - $router is a “router instance” object that includes hop methods, hook functions, etc
Hash and History modes
-
Hash mode: In the browser, the symbol “#” is called a hash, and the characters after # are read with window.location.hash. Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages.
-
History mode: History uses new HTML5 features; Two new methods are provided: pushState(), replaceState() to modify the browser history stack, and popState events to listen for state changes.
-
In hash mode (http://localhost:8080#home), even if no configuration is required, the static server will always look for index.html and return it to us, and the Vue – Router will then take the character after # as an argument to transform the front page.
-
History pattern, what we want is: http://localhost:8080/home, but eventually return is index. The HTML, and then the vue – the router will get home as a parameter, to transform the front page. So who can do that in Nginx? The answer is try_files.
nginx
location / {
root /data/www/rf-blog-web;
index index.html;
try_files $uri $uri/ /index.html;
}
Copy the code
Apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Copy the code
node.js
const http = require('http')
const fs = require('fs')
const httpPort = 80
http
.createServer((req, res) = > {
fs.readFile('index.htm'.'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.htm" file.')
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
})
.listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
Copy the code
Switching routes dynamically changes the title
In the mixed application with H5 embedded in app, the title in the webview of some apps in iOS system cannot be modified by document.title = XXX, because the title of the page is only loaded once in iOS WebView, and dynamic change is invalid.
- Install dependencies
npm install vue-wechat-title --save
Copy the code
- In the main. Use js
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
Copy the code
- Configure the route meta object to configure the title and listen on the route guard
router.afterEach(route= > {
// Get the title attribute from the route meta-information
if (route.meta.title) {
document.title = route.meta.title
// For iOS devices, use the following hack to update the page title
if (navigator.userAgent.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/)) {
const hackIframe = document.createElement('iframe')
hackIframe.style.display = 'none'
hackIframe.src = '/static/html/fixIosTitle.html? r=' + Math.random()
document.body.appendChild(hackIframe)
setTimeout(_= > {
document.body.removeChild(hackIframe)
}, 300)}}})Copy the code
- Modify router-view in app. vue
<router-view v-wechat-title="$route.meta.title"></router-view>
Copy the code
scrollBehavior
With front-end routing, you want the page to roll to the top when switching to a new route, or to keep the original scrolling position, as if the page were being reloaded. Vue-router can do this, and better, by letting you customize how the page scrolls when switching routes.
const router = new VueRouter({
routes: [...]. , scrollBehavior (to,from, savedPosition) {
// return is expected to scroll to the position}})Copy the code
The scrollBehavior method receives to and FROM routing objects. The third parameter savedPosition is available if and only if popState navigation (triggered by the browser’s forward/back buttons).
With keepAlive, if keepAlive, to save the stay position:
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
if (from.meta.keepAlive) {
from.meta.savedPosition = document.body.scrollTop
}
return { x: 0.y: to.meta.savedPosition || 0}}}Copy the code
keep_alive
Keep-alive is an abstract component provided by Vue. It is used to cache components to save performance. Since it is an abstract component, the V page will not be rendered as a DOM element after rendering.
<keep-alive>
<router-view></router-view>
</keep-alive>
Copy the code
The lifecycle hook functions activated and deactivated are executed when a component is switched in keep-alive
parameter
- Include: string or regular expression. Only matching components are cached.
- Exclude: indicates a string or regular expression. Any matching components will not be cached.
<keep-alive include="a,b">
<router-view></router-view>
</keep-alive>
<keep-alive exclude="c">
<router-view></router-view>
</keep-alive>
Copy the code
The include attribute indicates that only components whose names are a and B will be cached. Other components will not be cached. The exclude attribute indicates that all components will be cached except those whose name attribute is C.
Use the keepAlive attribute of $route.meta
You need to set the meta of the router in the router
export default new Router({
routes: [{path: '/'.name: 'Hello'.component: Hello,
meta: {
keepAlive: false // No caching is required}}, {path: '/page1'.name: 'Page1'.component: Page1,
meta: {
keepAlive: true // Need to be cached}}}])Copy the code
Make a distinction between cached and uncached pages in app.vue
<div id="app">
<router-view v-if=! "" $route.meta.keepAlive"></router-view>
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
</div>
Copy the code