Vue - Summary of Routing-related Knowledge Points

Article Directory

  • foreword
  • 1. What is routing
  • Second, the installation and use of routing
    • 1. Install
    • 2 mount in main.js
    • 3. Create a routing component
  • 3. Routing parameters
    • 1. The type of params
    • 2. The type of Query parameter
    • 3. route name
  •  4. Programmatic Routing
  • 5. Cache Routing Components
  • 6. Routing Guard
    • 1. Front guard
    • 2. Back guard
  • Summarize

1. What is routing?

Vue Router is   the official router for Vue.js. It is deeply integrated with Vue.js core, making it easy to build single-page applications with Vue.js.

   Related terms:

  • Routing: route A set of key-v correspondences (the components corresponding to path changes are switched)
  • Router: router Multiple routes need router management
  • In order to implement Single Page Application (SPA)

   Features include:

  • Nested route-maps
  • dynamic routing
  • Modular, component-based routing configuration
  • Route parameters, queries, wildcards
  • Show transition effects provided by Vue.js' transition system
  • Detailed Navigation Controls
  • Automatically activate links with CSS classes
  • HTML5 history mode or hash mode
  • Customizable scrolling behavior
  • Correct Encoding of URLs

Second, the installation and use of routing

1. Install

npm i vue-router@3 install version 3

Create a router directory in the src root directory, and create index.js in the directory. The code is as follows:

import Vue from 'vue';
//导入vue-router
import VueRouter from 'vue-router'

//应用插件
Vue.use(VueRouter)

//创建router规则对象
const routes = [
	
]
//创建router
const router = new VueRouter({
	routes
})

//导出router
export default router

2. Mount in main.js

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false

import router from './router'
new Vue({
  render: h => h(App),
  router,
}).$mount('#app')

3. Create a routing component

Create folder pages under src root directory

   illustrate:

  • Routing component pages
  • General components
  • The routing component has two more attributes: $route $router

   Routing rules related writing method:

// 引入vue
import Vue from 'vue';
// 导入 vue-router
import VueRouter from 'vue-router';

// 导入组件
import About from '../pages/About';
import ContactUs from '../pages/ContactUs';

import Persons from '../pages/Persons';

import Show from '../pages/Show'
// 应用插件
Vue.use(VueRouter);

// 创建router规则对象
const routes =[
{
    path:'/about',
    component: About
},
{
    path:'/contactus',
    component: ContactUs
},
{
    path:'/persons/:id/:realname',
    component:Persons,
    children:[
        {
            path:'show',
            component:Show
        }
    ]
}
]

// 创建router
const router = new VueRouter({
    routes,
})

// 导出router
export default router

  use routing  

This tag is a built-in component in vue-router, and it will be rendered as an <a> tag.

<router-link to="/about" active-class="hover">About Us</router-link>

This tag will dynamically render different components according to the current path, which is a placeholder for the component.

<router-view></router-view>

   router-link attribute:

  • to: used to specify the path to jump to.
  • tag: tag can specify what component will be rendered after <router-link>.
  • replace: replace will not leave history records, so when replace is specified, the back key cannot return to the previous page.
  • active-class: When the route corresponding to <router-link> matches successfully, a router-link-active class will be automatically set for the current element, and the default name can be modified by setting active-class.

   mode attribute  

  • Hash mode: Vue's routing defaults to hash mode, and there will be a # after the address bar.
  • history mode: mode=”history”/

the difference:

1: hash compatibility is good, history is not compatible with old version browsers

2: The # in the hash will not be sent to the server, but the history will be sent to the server. When the program is deployed and launched, the support of the back-end personnel is required to solve the 404 refresh problem. Configure the url redirection of apache or nginx to redirect to your home page route.

   Default path - that is, the content displayed by default on the page  

{

          path: '/',

          redirect: '/about'

},

3. Routing parameters

1. The type of params

Configure the routing format in the routing rule: /router/:id/:title (dynamic routing)

Set props to true and receive data

Address bar display style - /xxx/xxx/1/Zhangsan

Template code sample code:

<router-link :to="`/message/show/${item.id}`">{ {item.realname}}</router-link>

  Routing props configuration  

  • The first type: props: {id: 10, title: 'ttt'}
  • The second type: props: true The parameters of the params of the route are passed to the props of the component
  • The third value is a function (the query parameter below is demonstrated)

props($route){

  return {id:$route.query.id,title:$route.query.title}

}

2. Types of Query parameters

   String form:

<li v-for="item in res">

<router-link :to="`/about/news/show?id=${item.id}&title=${item.title}`">{
    
    {item.title}}</router-link>

</li>

    Parameter reception:

 methods:{
        id( ){
            return $route.query.id;
        },
        title( ){
            reutrn $route.query.title;
        }
    }

3. route name

Function - Simplify the jump of the route, use a longer name for the route

The above query jump is recommended to be written as follows:

<router-link  :to="{name:'show',
query:{id:item.id,title:item.realname}}">{
    
    {item.realname}}
</router-link>

 4. Programmatic Routing

When it is not a tag, js code is needed to jump, so we use programmatic routing. Two ways: replace and push.

1: String form

this.$router.push(`/message/show/${item.id}/${item.realname}`);

2: Object form

this.$router.push({

                                        name:'show',

                                        params:{

                                                id:item.id,

                                                title:item.title

                                        }

})

3: this.$router.back();//Back

        this.$router.forward(); //forward

        this.$router.go(); //The parameter can be a number, specifying to jump to the specified page

5. Cache Routing Components

Function - keep the component active without destroying it.

Related parameters:

Include If not written, keep all components active and not destroyed.

Multiple components use an array, :include="['component 1','component 2']"

<keep-alive include=”组件名称”>
     <router-view></router-view>
</keep-alive>

Two hook functions for routing:

//Component switch in (component display status)

activated() {

                        this.myinter =  setInterval(()=>{

                                        console.log(1)

                                },100);

},

//Component switch out (background display)

deactivated() {

                        clearInterval(this.myinter);

}

6. Routing Guard

The navigation guard provided by vue-router is mainly used to guard the navigation by jumping or canceling. There are many ways to implement route navigation: globally, specific to a single route, or at the component level.

1.1 Front guard

That is, it will take effect for all routes in the entire single-page application (SPA), executed at initialization, and executed before each routing switch.

代码:

//前置路由守卫

router.beforeEach((to,from,next)=>{

        // console.log(to);

        // console.log(from);

        if(to.name=="news" || to.name=="dt"){

                if(localStorage.getItem("token")=="zs"){

                        next();

                }

        }else{

                next();

        }

})

  Parameters in the function:

  • to: which route to enter.
  • from: which route to leave from.
  • next: function, decide whether to display the routing page you want to see.

  meta attribute:  

Routing custom information:

It is used to mark whether the route needs to judge whether the guard intercepts, meta() (for developers to add custom information)

2.2 Back guard

Global post guard: Execute at initialization, after each routing switch

2.2.1  Exclusive route guard

It is the same as the global route guard, but it can only be used for one route.

2.2.2 Routing guards in components

Component guards (the two methods of component guards are at the same level as lifecycle functions);

Called when entering the route, the component instance this cannot be obtained at this time, because the component instance has not been created before the current guard is executed.

   //Through the routing rules, call when entering the component  

beforeRouteEnter(to,from,next){

 next(vm => {

    // access component instance via `vm`

  })

}

   //Through the routing rules, call when leaving the component  

beforeRouteLeave(to,from,next){

}

Guess you like

Origin blog.csdn.net/Bonsoir777/article/details/127344626