Basic use of vue day 5 routing; Route redirect; Nested routing practices (children); Dynamic matching route (id,props,$route.params.id); Named route; Programming navigation usage

---------------------Basic concepts and principles------------------------

1.1 routing

Routing is a broad and abstract concept. The essence of routing is correspondence.
In development, routing is divided into:

  1. Back end routing
    Concept: return different contents according to different user URL requests
    Essence: the correspondence between the URL request address and the server resource
  2. Front end routing
    Concept: display different page contents according to different user events
    Essence: the correspondence between user events and event handling functions
  3. Simple front-end routing
    Implementation based on hash in URL (change the hash of URL when clicking the menu, and control the switching of components according to the change of hash)
        // Listen to the onhashchange event of window and switch the name of the component to be displayed according to the latest hash value obtained
        window.onhashchange = function() {
            // Via location Hash get the latest hash value
            switch (location.hash.slice(1)) {
                case '/zhuye':
                    vm.comName = 'zhuye'
                    break
                case '/keji':
                    vm.comName = 'keji'
                    break
                case '/caijing':
                    vm.comName = 'caijing'
                    break
                case '/yule':
                    vm.comName = 'yule'
                    break
            }
        }

1.2 SPA(Single Page Application)

  1. Back end rendering (performance issues)
  2. Ajax front-end rendering (front-end rendering improves performance, but does not support browser forward and backward operations)
  3. SPA (Single Page Application): there is only one page in the whole website. The change of content is realized through Ajax local update. At the same time, it supports the forward and backward operation of browser address bar
  4. One of the implementation principles of SPA: hash based on URL address (the change of hash will lead to the change of browser's access history, but the change of hash will not trigger a new URL request)
  5. In the process of implementing SPA, the core technology point is front-end routing

---------------------Basic of Vue router-----------------------

2.1 basic use steps

  1. Import relevant library files (pay attention to the order, vue.js should be in front)
<!-- Import vue File, global window Object mount Vue Constructor --> 
<script src="./lib/vue_2.5.22.js"></script>
<!-- Import vue-router File, global window Object mount VueRouter Constructor -->
<script src="./lib/vue-router_3.0.2.js"></script>
  1. Add routing link (similar to a label)
<!-- router-link yes vue The labels provided in will be rendered as by default a label -->
<!-- to Attributes are rendered as by default href attribute -->
<!-- to The value of the attribute is rendered as by default # The initial hash address -- > < router link to = "/ user" > User < / router link >
<router-link to="/register">Register</router-link>
  1. Add route fill bit (placeholder)
<!-- Route padding bit (also known as route placeholder) -->
<!-- In the future, components matched by routing rules will be rendered to router-view Location --> 
<router-view></router-view>
  1. Define the routing component (the content displayed in the placeholder, pay attention to the initial capitalization)
 	var User = {
		 template: '<div>User</div>'
	 }
	 var Register = {
		 template: '<div>Register</div>'
	 }
  1. Configure routing rules and create routing instances
 // Create routing instance object 
 var router = new VueRouter({
 // routes is an array of routing rules
	 routes: [
 // Each routing rule is a configuration object, which contains at least two attributes: path and component:
 // path indicates the hash address matched by the current routing rule
 // Component indicates the component to be displayed corresponding to the current routing rule
		 {path:'/user',component: User},
		 {path:'/register',component: Register}
	 ]
 })
  1. Mount the route to the Vue root instance
 new Vue({
 el: '#app',
 // In order for the routing rules to take effect, the routing object must be mounted on the vue instance object
 router  // Equivalent to router: router, because the instance name is equal to router
 });

2.2 route redirect

Routing redirection refers to forcing the user to jump to address C when accessing address A, so as to display A specific component page;
By specifying a new routing address through the redirect attribute of the routing rule, you can easily set the redirection of the route:

	var router = new VueRouter({
		 routes: [
 // Where, path indicates the original address to be redirected, and redirect indicates the new address to be redirected
			 {path:'/', redirect: '/user'},
			 {path:'/user',component: User},
			 {path:'/register',component: Register}
		 ]
     })

--------------------Vue router nested routing--------------------

3.1 nested route usage (children attribute)

1. Nested routing function analysis

  1. Click the parent route link to display the template content
  2. There are child routing links in the template content
  3. Click the sub level routing link to display the sub level template content

2. Parent routing component template

  1. Parent routing link
  2. Parent component routing fill bit
    <!-- cover vm The area controlled by the instance -->
    <div id="app">
        <router-link to="/user">User</router-link>
        <router-link to="/register">Register</router-link>

        <!-- Route placeholder -->
        <router-view></router-view>
    </div>

3. Sub level routing template (write another template in the sub template)

  1. Child routing link
  2. Child routing fill bit
        const Register = {
            template: `<div>
          <h1>Register assembly</h1>
          <hr/>

          <!-- Sub route link -->
          <router-link to="/register/tab1">tab1</router-link>
          <router-link to="/register/tab2">tab2</router-link>

          <!-- Placeholder for sub route -->
          <router-view />
        <div>`
        }

4. Nested routing configuration (children)

  1. The parent route configures the child route through the children attribute
        // Create routing instance object
        const router = new VueRouter({
            // All routing rules
            routes: [{
                    path: '/',
                    redirect: '/user'
                }, {
                    path: '/user',
                    component: User
                },
                // The children array represents the sub routing rules
                {
                    path: '/register',
                    component: Register,
                    children: [{
                        path: '/register/tab1',
                        component: Tab1
                    }, {
                        path: '/register/tab2',
                        component: Tab2
                    }]
                }
            ]
        })

--------------------Vue router dynamic route matching--------------------

4.1 basic usage of dynamic matching route (id and $route.params.id)

Application scenario: route matching through the mode of dynamic route parameters

var router = new VueRouter({
	 routes: [
	 // Dynamic path parameters start with a colon
		 { path: '/user/:id', component: User }
	 ]
})

const User = {
	 // Route component through $route Params get routing parameters
	 template: '<div>User {{ $route.params.id }}</div>'
}

4.2 routing component transfer parameters (id and props:true and props: ['id'])

$route is highly coupled with the corresponding route, which is not flexible enough, so props can be used to decouple components and routes

  1. The value of props is Boolean (only id can be passed)
	const router = new VueRouter({
		 routes: [
		 // If props is set to true, route Params will be set as the component property
			 { path: '/user/:id', component: User, props: true }
		 ]
	 })
	const User = {
		 props: ['id'], // Receive routing parameters using props
		 template: '<div>user ID: {{ id }}</div>' // Use routing parameters
	 }
  1. The value of props is the object type (this type cannot pass id, but only the value in the object)
	 const router = new VueRouter({
		 routes: [
		 // If props is an object, it will be set as is as a component property
			 { path: '/user/:id',
			  component: User, 
			  props: { uname: 'lisi', age: 12 }}
		 ]
	 })
	const User = {
		 props: ['uname', 'age'],
		 template: '<div>User information:{{ uname + '---' + age}}</div>'
	 }
  1. The value of props is the function type (the value and id in the object can be passed)
	 const router = new VueRouter({
		 routes: [
		 // If props is a function, this function receives the route object as its own formal parameter
			 { path: '/user/:id', 
			   component: User, 
			   props: route => (
			   { uname: 'zs', age: 20, id: route.params.id })
			 }
		 ]
 	 })
	const User = {
		 props: ['uname', 'age', 'id'],
		 template: 
		 '<div>User information:{{ uname + '---' + age + '---' + id}}</div>'
	 }

--------------------Vue router named route--------------------

6.1 configuration rules for named routes (name: ')

In order to more conveniently represent the path of the route, you can give an alias to the routing rule, that is, "named route".

    <!-- cover vm The area controlled by the instance -->
    <div id="app">
        <router-link to="/user/1">User1</router-link>
        <router-link to="/user/2">User2</router-link>
        <router-link :to="{ name: 'user', params: {id: 3} }">User3</router-link>
        <router-link to="/register">Register</router-link>

        <!-- Route placeholder -->
        <router-view></router-view>
    </div>

    <script>
        const User = {
            props: ['id', 'uname', 'age'],
            template: '<h1>User assembly -- user id by: {{id}} -- Name is:{{uname}} -- Age:{{age}}</h1>'
        }

        const Register = {
            template: '<h1>Register assembly</h1>'
        }

        // Create routing instance object
        const router = new VueRouter({
            // All routing rules
            routes: [{
                path: '/',
                redirect: '/user'
            }, {
                // Named route
                name: 'user',
                path: '/user/:id',
                component: User,
                props: route => ({
                    uname: 'zs',
                    age: 20,
                    id: route.params.id
                }) // router. Short for push ({Name: 'user', params: {ID: 123}})
            }, {
                path: '/register',
                component: Register
            }]
        })

        // Create vm instance object
        const vm = new Vue({
            // Specify the area to control
            el: '#app',
            data: {},
            // Mount routing instance object
            // router: router
            router
        })
    </script>

--------------------Vue router programmed navigation-------------------

5.1 two ways of page navigation

  1. Declarative navigation: the way to navigate by clicking a link is called declarative navigation
    For example, < a > link in ordinary web pages or < router link > in vue
  2. Programmed navigation: the way to realize navigation by calling the API in the form of JavaScript is called programmed navigation
    For example: location. In ordinary web pages href

5.2 basic usage of programmed navigation (router.push())

Common programmatic navigation API s are as follows:

  1. this.$router.push('hash address')
  2. this.$router.go(n)
	 const User = {
		 template: '<div><button @click="goRegister">Jump to the registration page</button></div>',
		 methods: {
			 goRegister: function(){
			 // Control route jump by programming
				 this.$router.push('/register');
			 }
		 }
	 }

5.3 programmed navigation parameter rules

router. Parameter rules of push() method

 // String (path name)
 router.push('/home')
 // object
 router.push({ path: '/home' })
 // Named route (pass parameters)
 router.push({ name: '/user', params: { userId: 123 }})
 // With query parameters, it becomes / register?uname=lisi
 router.push({ path: '/register', query: { uname: 'lisi' }})

--------------------The case of Vue router-------------------

Case: background management routing case

1. Key points of routing technology used:

  1. Basic usage of routing
  2. Nested Route
  3. Route redirection
  4. Routing parameters
  5. Programming navigation

2. Divide the component structure according to the overall layout of the project, and control the display of components through route navigation

  1. Detach and render App root components
  2. Transform the left menu into routing links
  3. Create the routing component corresponding to the menu on the left
  4. Add a route placeholder in the body area on the right
  5. Add sub routing rule
  6. Redirect default render user components through routing
  7. Render user list data
  8. Programmatically navigate to the user details page
  9. Realize the backward function
    <!-- To be vue The area controlled by the instance -->
    <div id="app">
        <!-- Route placeholder -->
        <router-view></router-view>
    </div>

    <script>
        // Define APP root components
        const App = {
            template: `<div>
          <!-- Head area -->
          <header class="header">Intelligent background management system</header>
          <!-- Middle main area -->
          <div class="main">
            <!-- Left menu bar -->
            <div class="content left">
              <ul>
                <li><router-link to="/users">user management </router-link></li>
                <li><router-link to="/rights">Authority management</router-link></li>
                <li><router-link to="/goods">Commodity management</router-link></li>
                <li><router-link to="/orders">Order management</router-link></li>
                <li><router-link to="/settings">System settings</router-link></li>
              </ul>
            </div>
            <!-- Right content area -->
            <div class="content right"><div class="main-content">
              <router-view /> 
            </div></div>
          </div>
          <!-- tail area  -->
          <footer class="footer">Copyright information</footer>
        </div>`
        }

        const Users = {
            data() {
                return {
                    userlist: [{
                        id: 1,
                        name: 'Zhang San',
                        age: 10
                    }, {
                        id: 2,
                        name: 'Li Si',
                        age: 20
                    }, {
                        id: 3,
                        name: 'Wang Wu',
                        age: 30
                    }, {
                        id: 4,
                        name: 'Zhao Liu',
                        age: 40
                    }]
                }
            },
            methods: {
                goDetail(id) {
                    console.log(id)
                    this.$router.push('/userinfo/' + id)
                }
            },
            template: `<div>
        <h3>User management area</h3>
        <table>
          <thead>
            <tr><th>number</th><th>full name</th><th>Age</th><th>operation</th></tr>
          </thead>
          <tbody>
            <tr v-for="item in userlist" :key="item.id">
              <td>{{item.id}}</td>
              <td>{{item.name}}</td>
              <td>{{item.age}}</td>
              <td>
                <a href="javascript:;" @click="goDetail(item.id)">details</a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>`
        }

        const UserInfo = {
            props: ['id'],
            template: `<div>
          <h5>User details page --- user Id For:{{id}}</h5>
          <button @click="goback()">back off</button>
        </div>`,
            methods: {
                goback() {
                    // Realize the backward function
                    this.$router.go(-1)
                }
            }
        }

        const Rights = {
            template: `<div>
        <h3>Permission management area</h3>
      </div>`
        }
        const Goods = {
            template: `<div>
        <h3>Commodity management area</h3>
      </div>`
        }
        const Orders = {
            template: `<div>
        <h3>Order management area</h3>
      </div>`
        }
        const Settings = {
            template: `<div>
        <h3>System setting area</h3>
      </div>`
        }

        // Create routing object
        const router = new VueRouter({
            routes: [{
                path: '/',
                component: App,
                redirect: '/users',
                children: [{
                    path: '/users',
                    component: Users
                }, {
                    path: '/userinfo/:id',
                    component: UserInfo,
                    props: true
                }, {
                    path: '/rights',
                    component: Rights
                }, {
                    path: '/goods',
                    component: Goods
                }, {
                    path: '/orders',
                    component: Orders
                }, {
                    path: '/settings',
                    component: Settings
                }]
            }]
        })

        const vm = new Vue({
            el: '#app',
            router
        })
    </script>

Keywords: Vue

Added by ac1dsp3ctrum on Fri, 18 Feb 2022 03:43:49 +0200