Vue Learning Notes--Basic Use of Vue-Router

1. SPA(Single Page Application)

  • Better performance than back-end rendering
  • Ajax front-end rendering, browser forward and backward operations are not supported
  • SPA Single Page Application: There is only one page in the whole system, the content changes are local refresh through Ajax asynchronous request, and support browser address bar forward and backward operation
  • hash based on URL is the implementation principle of SPA
  • Front-end routing is the basis for also SPA implementation

2. Basic use of Vue-Router

Code Instances

<!--1-1. First introduced vue.js file-->
<script src="js/vue.js"></script>
<!--1-2. Reintroduction vue-router.js file-->
<script src="js/vue-router.js"></script>

<div id="app">
    <!--2. Add Routing Link-->
    <router-link to="/user">User</router-link>
    <router-link to="/register">Register</router-link>

    <!--3. Add Route Fill Placeholder-->
    <router-view></router-view>
</div>

<script>
    // 4-1. Define Routing Component--User Component
    const User = {
      template: '<h1>User assembly</h1>'
    }

    // 4-2. Define Routing Component--Register Component
    const Register = {
      template: '<h1>Register assembly</h1>'
    }

    // 5. Create Vue-Router component objects and configure routing rules
    const pathRouter = new VueRouter({
      routes: [
        {path: '/user', component: User},
        {path: '/register', component: Register}
      ]
    });

    const vm = new Vue({
      el: '#app',
      data: {

      },
      // 6. Mount the VueRouter instance object onto the Vue instance object
      router: pathRouter
    });
</script>

2-1.Steps for using Vue-Router:

  1. IntroduceVue.jsAnd vue-Router.jsFile, <script src="js/vue.js"></script>precedes <script src=" js/vue-router.js"></script>introduced because Vue-Router depends on Vue
  2. Using the <router-link>tag, add a routing connection, <router-link to="/user">User</router-link>, Vue will replace <router-link>with <a> by default, and replace to="/user" with href="#/user"
  3. With <router-view>, Vue displays the content corresponding to the value of the to attribute of <router-link> at the location of <>router-view>
  4. Define the routing component according to the declarative syntax of the Vue component
  5. Create a VueRouter routing instance object and configure the routing components defined in step 4 into the routing instance object
  6. Mount the VueRouter instance object onto the Vue instance object

2-2.Vue-Router Routing Redirection Function

With the redirect function, we can configure what the page needs to show the first time it opens, which is 2-1.Step 4 of the Vue-Router Usage Step Configure in the Definition Routing component.Add as follows:

// Create Vue-Router Component Object
const pathRouter = new VueRouter({
  routes: [
    {path: '/', redirect: '/user'}, // Route redirection configuration redirects requests to access path'/'to path/user'
    {path: '/user', component: User},
    {path: '/register', component: Register}
  ]
});

3.Vue-Router routing nesting

Routing nesting refers to the implementation of code examples where routing components are also present on a page rendered by a routing component

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

<div id="app">
    <router-link to="/userLogin">User Login</router-link>
    <router-link to="/register">User Register</router-link>

    <router-view></router-view>
</div>
<script>
const userLogin = {
  template: '<h1>User Login</h1>'
}

const userRegister = {
  template: `
    <div>
      <h1>User registration</h1>
      <hr/>

      <router-link to="/register/link1">Link1</router-link>
      <router-link to="/register/link2">Link2</router-link>

      <router-view />
    </div>
  `
}

const link1 = {
  template: '<h3>link1</h3>'
}

const link2 = {
  template: '<h3>link2</h3>'
}

const pathRouter = new VueRouter({
  routes: [
    {path: '/user', component: userLogin},
    {path: '/register', component: userRegister, children: [
      {path: '/register/link1', component: link1},
      {path: '/register/link2', component: link2}
    ]}
  ]
});

var vm = new Vue({
  el: '#app',
  data: {

  },
  router: pathRouter
});
</script>

Use children in routing definition rules to specify routing rules for subroutes

{path: '/register', component: userRegister, 
 children: [
      {path: '/link1', component: link1},
      {path: '/link2', component: link2}
 ]
}

3-1. Multilevel routing nesting

If there is multi-level nesting, you can continue to nest, and the three-level nesting code is as follows:

<script>
    const userLogin = {
      template: '<h1>User Login</h1>'
    }

    const userRegister = {
      template: `
        <div>
          <h1>User registration</h1>
          <hr/>

          <router-link to="/register/link1">Link1</router-link>
          <router-link to="/register/link2">Link2</router-link>

          <router-view />
        </div>
      `
    }

    const link1 = {
      template: `
      <div>
        <h3>link1</h3>
        <hr/>

        <router-link to="/register/link1/link1-1">Link1-1</router-link>
        <router-link to="/register/link1/link1-2">Link1-2</router-link>

        <router-view />
      </div>`
    }

    const link2 = {
      template: '<h3>link2</h3>'
    }

    const link1_1 = {
      template: '<h5>link1-1</h5>'
    }

    const link1_2 = {
      template: '<h5>link1-2</h5>'
    }

    const pathRouter = new VueRouter({
      routes: [
        {path: '/user', component: userLogin},
        {path: '/register', component: userRegister, children: [
          {path: '/register/link1', component: link1, children: [
            {path: '/register/link1/link1-1', component: link1_1},
            {path: '/register/link1/link1-2', component: link1_2}
          ]},
          {path: '/register/link2', component: link2}
        ]}
      ]
    });
  </script>

The code defined in the routing rule shows that we see three levels of routing nested code:

routes: [
    {path: '/user', component: userLogin},
    {path: '/register', component: userRegister,
     children: [
          {path: '/register/link1', component: link1,
         children: [
            {path: '/register/link1/link1-1', component: link1_1},
            {path: '/register/link1/link1-2', component: link1_2}
           ]
        },
          {path: '/register/link2', component: link2}
     ]
    }
]

4.Vue-Router Dynamic Routing Matching

In the case where multiple paths correspond to the same path component, Vue provides the capability of dynamic routing, which implements the relationship between multiple paths and a routing component, coded as follows:

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

<div id="app">
  <router-link to="/page/1">Page1</router-link>
  <router-link to="/page/2">Page2</router-link>
  <router-link to="/page/3">Page3</router-link>
  <router-link to="/query">Query</router-link>

  <router-view></router-view>
</div>
<script>
    var pageCom = {
      template: `
        <h1>Page {{ $route.params.pid }}</h1>
      `
    }

    var queryCom = {
      template: `
        <div>
          <h1>Query Page</h1>
          <hr/>

          <router-link to="/query/1">Query 1</router-link>
          <router-link to="/query/2">Query 2</router-link>

          <router-view></router-view>
        </div>
      `
    }

    var queryPage = {
      template: '<h3>Query Page{{ $route.params.qid }}</h3>'
    }

    var router = new VueRouter({
      routes: [
        {path: '/page/:pid', component: pageCom},
        {path: '/query', component: queryCom,
          children: [
            {path: '/query/:qid', component: queryPage}
          ]
        }
      ]
    });

    var vm=new Vue({
      el:'#app',
      data:{},
      methods:{},
      router
    });
</script>

For paths <router-link to="/page/1">Page1</router-link>, <router-link to="/page/2">Page2</router-link>and <router-link to="/page/3">Page3</router-link>the corresponding routing components are:

var pageCom = {
  template: `
    <h1>Page {{ $route.params.pid }}</h1>
  `
}

Therefore, dynamic routing configuration can be done in the routing rules of the VueRouter instance:

routes: [
    {path: '/page/:pid', component: pageCom},
    ...
}

In routing rules: PID is a dynamic parameter, and the values of parameters vary depending on the path.{{$in the corresponding routing componentRoute.params.pid}}, where $Route.paramsGet the fixed content of the parameter from Vue-Router, and the.Pid is consistent with the dynamic parameter name in the routing rule.

5. Vue-Router parameter transfer

Dynamic routing is where multiple paths correspond to the same routing component, that is, for routing components, there are variable parameters in the path, and getting the variable parameters in the path in the routing component requires {{route.params. [parameter name]}} to get.In addition to passing parameters through dynamic routes, Vue-Router provides the following methods of parameter delivery:

  1. By routing rule props attribute value Boolean type pass parameters
  2. By routing rule props attribute value Object type pass parameters
  3. By routing rule props attribute value Function Type Pass-Through Parameters

5-1. The props attribute value is a Boolean type

Code Samples

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

<div id="app">
    <router-link to="/item/1">Commodity 1</router-link>
    <router-link to="/item/2">Commodity 2</router-link>
    <router-link to="/item/3">Commodity 3</router-link>
    <router-link to="/query">Commodity Query</router-link>

    <router-view></router-view>
</div>
<script>
    var itemCom = {
        props: ['id'],
        template: `
        <div>
            <h1>commodity{{id}}</h1>
        </div>
        `
    }

    var queryCom = {
        template: '<h1>Commodity Query</h1>'
    }

    var router = new VueRouter({
        routes: [
            {path: '/item/:id', component: itemCom, props: true},
            {path: '/query/', component: queryCom}
        ]
    });

    var vm=new Vue({
        el:'#app',
        data:{},
        methods:{},
        router
    });
</script>

The main configuration for parameter delivery in the above code is to add props: true to the routing rule, and props: ['id']'to the component declaration.

5-2. Pros attribute value is object type

Code Samples

<div id="app">
  <router-link to="/item/1">Test Item 1</router-link>
  <router-link to="/item/2">Testing commodity 2</router-link>
  <router-link to="/item/3">Test Item 3</router-link>

  <router-view></router-view>
</div>
<script>
  const itemCom = {
    props: ['id', 'name', 'price'],
    template: `
      <div>
        //Commodity Page <br>
        //Commodity ID: {{id}} -- Commodity name: {{name}} -- Commodity price: {{price}} Yuan
      </div>
    `
  }

  const router = new VueRouter({
    routes: [
      {path: '/item/:id', component: itemCom, props: {name: 'Test Item 1', price: 20}}
    ]
  });

  var vm=new Vue({
    el:'#app',
    data:{},
    methods:{},
    router
  });
</script>

Boolean props configuration allows parameters for dynamic routing to be passed to components.If you want to pass other parameters, you need to specify props as the object type: {path:'/item/:id', component: itemCom, props: {name:'test commodity 1', price: 20}}, and you also need to add props: ['id','name','price'] to the routing component declaration.There are two types of explanatory parameters here, one is the dynamic path transfer parameter represented by id, and the other is the name price which represents the parameter passed through the props attribute.The corresponding ID can only pass through {{$route.params.id}} Get by

5-3. The props attribute value is a function type

Code Instances

<div id="app">
  <router-link to="/item/1">Commodity 1</router-link>
  <router-link to="/item/2">Commodity 2</router-link>
  <router-link to="/item/3">Commodity 3</router-link>

  <router-view></router-view>
</div>
<script>
    const itemCom = {
      props: ['id', 'name', 'price'],
      template: `
        <div>
          <h3>Commodity details</h3>
          //Commodity ID: {{id}}--Commodity name: {{name}}--Commodity price: {{price}}
        </div>
      `
    }

    const router = new VueRouter({
      routes: [
        {path: '/item/:id', component: itemCom, props: route => ({id: route.params.id, name:'Testing commodities', price: 30})}
      ]
    });

    var vm=new Vue({
      el:'#app',
      data:{},
      methods:{},
      router
    });
</script>

To achieve consistency in the form of parameters in the routing component, we use the function type of the props attribute by configuring props: route => ({id:Route.params.idIn the routing component, variable path parameters and routing rule configuration parameters can be obtained in the form of {{id}}, {{name}}, {{price}} consistently.

6. Vue-Router Named Routes

The name attribute is provided in the routing rule definition configuration to name the routing rule

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

<div id="app">
  <router-link :to='{name: "item", params:{id: 1, name: "Commodity 1", price: 30}}'>Commodity 1</router-link>
  <router-link :to='{name: "item", params:{id: 2, name: "Commodity 2", price: 40}}'>Commodity 2</router-link>
  <router-link :to='{name: "item", params:{id: 3, name: "Commodity 3", price: 10}}'>Commodity 3</router-link>

  <router-view></router-view>
</div>

<script>
    const itemCom = {
      props: ['id', 'name', 'price'],
      template: `
        <div>
          <h3> {{name}} </h3>
          <hr>
          //Commodity ID: {{id}} -- Commodity Name: {{name}} -- Commodity Price: {{price}}
        </div>
      `
    }

    const router = new VueRouter({
      routes: [
        {path: '/item/:id', name: 'item', component: itemCom, props: true}
      ]
    })

    var vm=new Vue({
      el:'#app',
      data:{},
      methods:{},
      router
    });
</script>
  1. Routing rules can be defined by naming them with the name attribute: {path:'/item/:id', name:'item', component: itemCom, props: true}.In the <router-link>tab, configure <router-link:to='{name:'item', params:{id: 2, name:'commodity 2', price: 40}'> commodity 2</router-link>, and the name attribute value should be the same as the name attribute value of the routing rule.
  2. In the to property of <router-link>we can also pass parameters through the params configuration item.For this parameter to be passed, props: true is added to the routing rule definition, and the to attribute is also bound by v-bind:(short:) so that the passed parameter can be obtained in the routing component.

7. Vue-Router programmatic and declarative navigation

  1. Declarative Navigation

Define connection information by <router-link>to achieve page jumps and navigation

  1. Programmatic Navigation

Navigation for page jumps through the API provided by Vue
Vue provided this.$router.push(url) and this.$router.go(n) Page jumps can be achieved.

7-1. Example of programmatic navigation

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

<div id="app">
  <router-link v-bind:to="{name: 'user', params: {id: 1, name: 'User 1', age: 16}}">User 1</router-link>
  <router-link :to="{name: 'user', params: {id: 2, name: 'User 2', age: 25}}">User 2</router-link>
  <router-link :to="{name: 'user', params: {id: 3, name: 'User 3', age: 24}}">User 3</router-link>
  <router-link :to="{name: 'reg'}">User registration</router-link>

  <router-view></router-view>
</div>
<script>
  const userCom = {
    props: ['id', 'name', 'age'],
    template: `<div>
        <h1> {{name}} </h1>
        //User ID: {{id}} -- User name: {{name}} -- User age: {{age}}
        <hr/>
        <button @click="userRegister">User Register</button>
      </div>`,
    methods: {
      userRegister() {
        this.$router.push("/register");
      }
    }
  }

  const registerCom = {
    template: `
      <div>
        <h1>User Register</h1>
        <button @click="back">Back off</button>
      </div>
    `,
    methods: {
      back() {
        console.log("aaaa");
      this.$router.go(-1);
    }
    }
  }

  const router = new VueRouter({
    routes: [
      {path: '/user/:id', name: 'user', component: userCom, props: true},
      {path: '/register', name: 'reg', component: registerCom}
    ]
  })

  var vm=new Vue({
    el:'#app',
    data:{},
    methods:{},
    router
  });
</script>

this.$router.push() Method parameter A URL of the page to jump to, this.$router.go(n), n is an integer, n is a negative number to step back to n, n is an integer to step forward n.this.$router.go(1) Equivalent toHistory.forward(), this.$router.go(-1) equalsHistory.back()

7-2. Programmatic navigation parameter transfer

this.$router.push() Parameter type:

  1. The string this.$router.push("/register");
  2. Object type this. $Router.push({path:'/register');
  3. Named Route this. $Router.push({name:'reg', params: {name:'Jack'}})
  4. Specify the query parameter this. $Router.push({path:'search', query: {name:'Jack'}}) This configuration will be translated by VUe to/search?name=Jack

**Description
If a path is provided, params will be ignored.Router.push(path:'/user', params: {userId}}) // ->/user, the above configuration does not pass userId parameters and parameter values to the target page.However, only the params configuration item, the query configuration item specifies parameters that can be passed
**

Tags: Javascript Vue Attribute

Posted on Sun, 07 Jun 2020 14:18:31 -0700 by Lokolo