Vue router -- 10 Vue router routing

Keywords: Vue

Vue router -- 10 Vue router routing

10.1 what is routing

Vue Router is the official routing manager of Vue.js. It is deeply integrated with the core of Vue.js, making it very easy to build a single page application.
By switching the display of different components to render pages according to different request paths.

 

10.2 basic routing usage

10.2.1   Install routing

npm install vue-router

10.2.2    Introduce vue-router.js

<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vue-router/dist/vue-router.js"></script>

10.2.3    HTML route switching

<div id="app">
        <div class="header">
            <h1>header</h1>
        </div>
        <div class="left">
            <ul>
                <!-- Mode 1: traditional mode! -->
                <li><a href="#/foo">foo</a></li>
                <li><a href="#/bar">bar</a></li>
                <!-- Method 2: official recommendation! -->
                <!-- <router-link> By default, it will be rendered as a `<a>` label, -->
                <!-- Pass in `to` Property to specify the jump link. You don't have to add it as above `#`Number -->
                <li><router-link to="/foo">Go to Foo</router-link></li>
                <li><router-link to="/bar">Go to Bar</router-link></li>
            </ul>
        </div>
        <div class="main">
            <!-- Route exit: the components to which the route matches will be rendered here -->
            <router-view></router-view>
        </div>
    </div>

10.2.4    JS configure routing

  <script src="./node_modules/vue/dist/vue.js"></script>
    <script src="./node_modules/vue-router/dist/vue-router.js"></script>
    <script>
        //1.Define components
        const Foo = {
            template:`<div>hello Foo</div>`
        };
        const Bar ={
            template:`<div>hello Bar</div>`
        }

        // 2. Configure routing table: when clicking a specific url The corresponding component is displayed.
        const router = new VueRouter({
            routes:[ //Configure one component per route map
                {path:'/foo',component:Foo},
                {path:'/bar',component:Bar}
            ]
        });

        // 3. Inject routes into instances
        new Vue({
            el:'#app',
            router //router:router
        });
    </script>

 

10.3 routing case practice

10.3.1 modify template

Install routing / axios

npm install vue-router

npm install axios

 

10.3.2 News component

**js function self calling; (function(){})()

**windows global attribute window.News = {}, so that the component can be called globally. Otherwise, it cannot be called outside the scope

;(function(){
    //
    const template=`<!--Master page area on the right-->
    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <div class="header clearfix">
            <nav>
              <ul class="nav nav-pills">
                <li class="active"><a href="#"> Sports</a></li>
                <li ><a href="#"> Technology</a></li>
              </ul>
            </nav>
            <hr>
          </div>
          
          <!--Sports column-->
        <div>
            <ul>
                <li>
                    <a href="#"> the World Cup begins</a>
                </li>
                <li>
                    <a href="#"> NBA start countdown</a>
                </li>
            </ul>
            <!--details-->
            <div class="jumbotron">
                <h2>The World Cup begins</h2>
                <p>The opening ceremony of the world cup will be held at 8 o'clock tomorrow evening.....</p>
            </div>
        </div>  
          <!--Science and technology column-->
        <div>
            <ul >
                <li>
                    <span>5G The time has come </span>
                    <button class="btn  btn-default btn-xs">see(Push)</button>&nbsp;
                    <button class="btn btn-default btn-xs">see(replace)</button>
                </li>
                <li>
                    <span>Internet shuffle</span>
                    <button class="btn  btn-default btn-xs">see(Push)</button>&nbsp;
                    <button class="btn  btn-default btn-xs">see(replace)</button>
                </li>
            </ul>
            <!--details-->
            <div class="jumbotron">
                <h2>The World Cup begins</h2>
                <p>The opening ceremony of the world cup will be held at 8 o'clock tomorrow evening.....</p>
            </div>
        </div>         
    </div>`;

    window.News={
        template
    }

})()

 

10.3.3 About component

; (function () {
    const template = `<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
        <h1>Dream Valley-Accompany you to study and dream!</h1>
        <input />
        </div>`;

    window.About={
        template
    }
    
})()

 

10.3.4 configuring routing

New router.js file

; (function () {

    window.router = new VueRouter({

        linkActiveClass: 'active',
        routes: [
            { path: '/', component: AppHome },
            { path: '/news', component: News },
            { path: '/about', component: About }
        ]
    })

})()

 

10.3.5 injecting routes into instances

  Introduce router in Vue instance in main.js

var vm = new Vue({
    el: '#app',
    // Vue In the instance template After the component is referenced in the option, the rendering result of this component will be replaced #Element of app tag
    // template: '<app> </app>',
    template:'<app></app>',
    router, // Reference routing configuration
    components:{
      App,
    }
  });

 

10.3.6 configure route rendering component exit

  Configure in App.js

; (function () {
    // The component template must contain one and only one root element
    const template = `
    <div>
        <!--Head navigation area-->
        <app-navbar></app-navbar>

        <!--Core area:Left and right-->
        <div class="container-fluid">
        <div class="row">

            <!--Left menu bar area-->
            <app-left></app-left>

            <!--Master page area on the right: It is divided into upper and lower areas
            <app-home>
                <h1 slot="dashboard" class="page-header">{{title}}</h1>
            </app-home>
            -->

            <!-- Configure the route rendering component exit, that is, the main page area on the right -->
            <router-view>
                <h1 slot="dashboard" class="page-header">{{title}}</h1>
            </router-view>

        </div>
        </div>
    </div>
    `;

    window.App = {
        template,
        components: {
            AppNavbar,
            AppLeft,
            AppHome
        },
        data() {
            return {
                title: 'Dashboard',
            };
        },
    }

})()

 

10.3.7 modify jump link

  Modify the jump link in AppLeft.js

; (function () {
window.AppLeaf = {
  template: `<div class="col-sm-3 col-md-2 sidebar">
    <ul class="nav nav-sidebar">
    <li class="active">
      <router-link to="/">home page</router-link>
    </li>
    <li>
      <router-link to="/news">News management</router-link>
    </li>
    <li>
      <router-link to="/about">About us</router-link>
    </li>
    </ul>
    </div>`
}
})()

 

10.3.8 importing js files

Pay attention to the order  

<script src="../node_modules/vue/dist/vue.js"></script>

  <!-- vue-router.js To introduce in vue.js Below--->
<script src="../node_modules/vue-router/dist/vue-router.js"></script> <script src="../node_modules/axios/dist/axios.js"></script> <script src="./components/AppNavbar.js"></script> <script src="./components/AppLeft.js"></script> <script src="./components/Home/DashBoard.js"></script> <script src="./components/Item.js"></script> <script src="./components/Home/HomeList.js"></script> <script src="./components/Home/AppHome.js"></script> <script src="./components/Home/News.js"></script> <script src="./components/Home/About.js"></script> <script src="./router.js"></script> <script src="./App.js"></script> <script src="./main.js"></script>

 

10.3.9 start up test

 http://127.0.0.1:5500/vue-08-router/02-bootstrap-ajax-router/index.html#/

 

10.4 style matching - highlight navigation

10.4.1 tag

< router link > generates < a > labels after default rendering.
You can use the tag attribute on < router link > to specify other labels to be generated after rendering.

 

10.4.2 active-class

< router link > the default CSS class name on the generated label after rendering: router link active.
You can use the active class attribute on < router link > to specify other class names generated after rendering.
You can configure the route globally through linkActiveClass, the route construction option. You do not need to use active class to specify generation in each < router link >
Class name of

 

10.4.3 exact

By default, the routing addresses /, / foo, / bar start with /, and they all match the CSS class name of / address.
You can use the exact attribute on < router link > to enable CSS class name exact matching.

<!-- This link will only be in the address / Activated when, -->
<router-link to="/" exact>

 

10.4.4 highlight navigation links

AppLeft.js

;(function(){

    const template=`<div class="col-sm-3 col-md-2 sidebar">
    <ul class="nav nav-sidebar">
    <!--
    router-link The default rendering is a label,
    If you need it to render other labels,You can use tag Property to specify the rendered label

    2. Can be in each router-link Use on active-class To activate CSS Class name 
    Or in VueRouter Instance,use linkActiveClass Global configuration CSS Class name 

    3. exact It's an exact match, Specify on which label,Then the path of this tag will not be fuzzy matched by other paths
    
    -->
    
      <router-link to="/" tag="li" exact><a>home page</a></router-link>
      <router-link to="/news" tag="li"><a>News management</a></router-link>
      <router-link to="/about" tag="li"><a>About us</a></router-link>
     
    </ul>
    
  </div>`;

    window.AppLeft={
        template
    }

})()

router.js

; (function () {

    window.router = new VueRouter({
        
        // Global configuration router-link Label generated CSS Class name
        linkActiveClass: 'active',
        routes: [
            { path: '/', component: AppHome },
            { path: '/news', component: News },
            { path: '/about', component: About }
        ]
    })

})()

 

10.5 nested routing

10.5.1 sub routing components

10.5.2 configuring nested routes

{
    path: '/news',
    component: News,
    children: [
        // When matched to /news/sport When requested,
        // assembly Sport Will be rendered in News In component <router-view> in
        {
        path: '/news/sport',
        component: Sport
        },
        // Abbreviation, equivalent to /news/tech Path, note that there is no / ,have / It's the root directory
        {
        path: 'tech',
        component: Tech
        },
        //Click news management to select news by default,
        // namely/news When there are no child paths, redirect Redirect to sports
        {
        path: '',
        redirect: '/news/sport'
        }
    ]
},
                

10.5.3 route jump link

<ul class="nav nav-pills">
<router-link to="/news/sport" tag="li">
<a >Sports</a>
</router-link>
<router-link to="/news/tech" tag="li">
<a >science and technology</a>
</router-link>
</ul>
<!--Define route exit-->
<router-view></router-view>

 

10.6 nested routing case - News Management

10.6.1 package components required for routing   Sport and Tech in New package

Sport.js

; (function () {
    //
    const template = `
    <div>
            <ul>
                <li v-for="(sport,index) in sportArr" :key="sport.id">
                    <a href="#" >{{ sport.title }}</a>
                </li>
                
            </ul>
            <!--details-->
            <div class="jumbotron">
                <h2>The World Cup begins</h2>
                <p>The opening ceremony of the world cup will be held at 8 o'clock tomorrow evening.....</p>
            </div>
    </div> 
    `;

    window.Sport = {
        template,
        data() {
            return {
                sportArr: [],
            };
        },
        created() {
           this.getSportArr();
        },
        methods:{
            getSportArr(){
                axios.get('http://127.0.0.1:5500/vue-08-router/02-bootstrap-ajax-router/db/sport.json').then(response => {
                    console.log(response.data) // Get the returned result data
                    this.sportArr = response.data
                }).catch(error => {
                    console.log(error.message)
                })
            }
        }
    }

})()

Tech.js

; (function () {

    //
    const template = `
    <div>
        <ul >
            <li v-for="(tech, index) in techArr" :key="tech.id">
                <span> {{tech.title}} </span>
                <button class="btn btn-default btn-xs">see(Push)</button>&nbsp;
                <button class="btn btn-default btn-xs">see(replace)</button>
            </li>
        </ul>
    <!--details-->
        <div class="jumbotron">
        <h2>The World Cup begins</h2>
        <p>The opening ceremony of the world cup will be held at 8 o'clock tomorrow evening.....</p>
        </div>
    </div>
    `;

    window.Tech = {
        template,
        data() {
            return {
                techArr: [],
            };
        },
        created() {
            this.getTechArr();
        },
        methods: {
            getTechArr() {
                axios.get('http://127.0.0.1:5500/vue-08-router/02-bootstrap-ajax-router/db/tech.json').then(response => {
                    console.log(response.data) // Get the returned result data
                    this.techArr = response.data
                }).catch(error => {
                    console.log(error.message)
                })
            }
        }
    }

})()

10.6.2 configuring nested routes

; (function () {

    window.router = new VueRouter({

        // Global configuration router-link Label generated CSS Class name
        linkActiveClass: 'active',
        routes: [
            { path: '/', component: AppHome },
            {
                path: '/news', component: News,
                children: [
                    {
                        path: '/news/sport', component: Sport
                    },
                    {
                        // In short, it is equivalent to the / news/tech path. Note that there is no /, and / is the root directory
                        path: 'tech', component: Tech
                    },
                    {
                        //Click news management to select news by default,
                        //When there is no sub path after / news, redirect to sports
                        path: '', redirect: '/news/sport'
                    }
                ]
            },
            { path: '/about', component: About }
        ]
    })

})()

10.6.3   Jump link and route rendering exit

;(function(){
    //
    const template=`<!--Master page area on the right-->
    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <div class="header clearfix">
            <nav>
              <ul class="nav nav-pills">
                <router-link to="/news/sport" tag="li" exact><a>Sports</a></router-link>
                <router-link to="/news/tech" tag="li" exact><a>science and technology</a></router-link>
              </ul>
            </nav>
            <hr>
          </div>

          <!--Define route exit-->
          <router-view></router-view>
    </div>`;

    window.News={
        template
    }

})()

10.6.4 introduction of JS

  <script src="./components/Home/Sport.js"></script>
  <script src="./components/Home/Tech.js"></script>

 

10.7 cache routing components and cases

10.7.1 scenario and function

1. By default, when the routing component is switched, the component instance will be destroyed, and the instance will be recreated when the switch comes back.
2. If the routing component instance can be cached, there is no need to reload the data after switching, which can improve the user experience.

 

10.7.2 implement cache routing component

< keep alive > can cache rendered routing component instances

<keep-alive>
    <router-view></router-view>
</keep-alive>

 

10.7.3 demo

Add the cache routing component in App.js in the demo of the appeal

<!-- Configure the route rendering component exit, that is, the main page area on the right -->
            <keep-alive>
            <router-view>
                <h1 slot="dashboard" class="page-header">{{title}}</h1>
            </router-view>
            </keep-alive>

 

10.8 data transmission by routing component

10.8.1 routing data transfer steps

(1) Routing configuration

{
  path: '/news/sport',
  component: Sport,
  children: [
    {
      path: '/news/sport/detail/:id', // :id Path variable placeholder
      component: SportDetail
    }
  ]
}

(2) Route jump path

<!--
To dynamically splice values, be to The attribute value is JS expression,
To write JS expression, Then use v-bind Mode binding properties
 be careful + Single quotation mark before ''
-->
<router-link :to="'/news/sport/detail/' + sport.id">
{{sport.title}}
</router-link>

(3) Read request parameters in routing component

this.$route.params.id

 

10.8.2 DEMO

Configure routing

; (function () {

    window.router = new VueRouter({

        // Global configuration router-link Label generated CSS Class name
        linkActiveClass: 'active',
        routes: [
            { path: '/', component: AppHome },
            {
                path: '/news', component: News,
                children: [
                    {
                        path: '/news/sport', component: Sport,
                        children: [
                            // : id path variable placeholder
                            { path: '/news/sport/detail/:id', component: SportDetail }
                        ]
                    },
                    {
                        // Abbreviation, equivalent to /news/tech Path, note that there is no / ,have / It's the root directory
                        path: 'tech', component: Tech,
                        children:[
                            {path: '/news/tech/detail/:id', component: TechDetail }
                        ]
                    },
                    {
                        //Click news management to select news by default,
                        //namely/news When there are no child paths, redirect Redirect to sports
                        path: '', redirect: '/news/sport'
                    }
                ]
            },
            { path: '/about', component: About }
        ]
    })

})()

Component specifies the path and render exit

; (function () {
    //
    const template = `
    <div>
            <ul>
                <li v-for="(sport,index) in sportArr" :key="sport.id">
                    <router-link :to="'/news/sport/detail/'+ sport.id" >
                       {{sport.title}}
                    </router-link>
                </li>
                
            </ul>

            <!--details-->
            <!--Define route exit-->
            <router-view></router-view>
    </div> 
    `;

    window.Sport = {
        template,
        data() {
            return {
                sportArr: [],
            };
        },
        created() {
           this.getSportArr();
        },
        methods:{
            getSportArr(){
                axios.get('http://127.0.0.1:5500/vue-08-router/02-bootstrap-ajax-router/db/sport.json').then(response => {
                    console.log(response.data) // Get the returned result data
                    this.sportArr = response.data
                }).catch(error => {
                    console.log(error.message)
                })
            }
        }
    }

})()

Detail component

; (function () {

    const template = `
    <div class="jumbotron">
        <h2>{{ sportDetail.title }}</h2>
        <p>{{ sportDetail.content }}</p>
    </div>
    `;

    window.SportDetail = {
        template,
        data() {
            return {
                id: null,
                sportDetail: {}
            };
        },
        created() {
            // be careful:
            // 1. yes $route , Finally, No r letter
            // 2. created The hook will only be called once. When switching the route of the title list, this hook will not be called again,
            // So corresponding ID Will not be updated and can be used watch monitor $route Routing changes.
            this.getItemById();
        },
        methods: {
            getItemById() {
                //Assign the variable of the routing path to the local variable
                this.id = this.$route.params.id - 0;
                var sportItem = [];
                axios.get('http://127.0.0.1:5500/vue-08-router/02-bootstrap-ajax-router/db/sport.json').then(response => {
                    //console.log(response.data) // Get the returned result data
                    sportItem = response.data;
                    this.sportDetail = sportItem.find(arr => {
                        return arr.id == this.id;
                    })
                    console.log(this.sportDetail);

                }).catch(error => {
                    console.log(error.message);
                })
            }
        },
        watch: { // watch Is an object used to listen for attribute usage
            // use watch monitor $route Routing changes,obtain ID value
            '$route': function () {
                //console.log('$route');
                if ((this.$route.params.id - 0) > 0) { //Determine whether it is a detail page route
                    this.getItemById()
                }

            }
        }
    }
})()

 

10.9 programming route navigation

10.9.1   Declarative and programmatic routing

**Declarative (specify link jump directly through < a > tag href)
<router-link :to="...">

**Programming (using js code link jump, such as localhost.href)
router.push(...)

 

10.9.2   Programmed route navigation API

this.$router.push(path) It is equivalent to clicking the routing link(Step back,It will return to the current routing interface)
this.$router.replace(path) Replace current route with new route(Step back,Cannot return to the current routing interface)
this.$router.back() Back to previous record route
this.$router.go(n) parameter n Specify the number of steps
this.$router.go(-1) Back to previous record route
this.$router.go(1) Forward to next record route

 

Posted by cool75 on Tue, 02 Nov 2021 21:23:14 -0700