[VUE] Routing router in vue.js

Foreword:

In this chapter we will introduce Vue.js routing to you.

Vue.js routing allows us to access different content through different URLs.

Through Vue.js, you can implement a multi-view single page web application (single page web application, SPA).

Vue.js routing needs to load  the vue-router library

Chinese document address: vue-router document .

1. Install router:

1. Direct download/CDN

https://unpkg.com/vue-router/dist/vue-router.js

2、CNPM

It is recommended to use Taobao mirror:

cnpm install vue-router  //会默认安装在node_modules文件中
//cnpm install -g vue-router //会安装在全局目录中(类似python的虚拟环境和全局环境)

2. Simple routing

  1. Create a routing rule file

    1. Path: src/router/index.js
  2. Mount router to vue instance

    1. Comment 5.2 in main.js file
  3. Route parameter type

    1. Path parameters (params can only introduce routes through name, path will be undefined)
    2. Query string parameters (query can introduce routes through name or path)
  4. Route jump

    1. Use router-link
    2. The to attribute can be a path path, a named route, as well as path parameters and query string parameters.
  5. case of element ui 

step:

1. Change the . in example. . . Paste into src/router/index.js

Route creation sites are placed in separate files components/router/index.js

// track number of popstate listeners
import Vue from 'vue'
import VueRouter from 'vue-router'

// 1. Use plugin.
// This installs <router-view> and <router-link>,
// and injects $router and $route to all router-enabled child components
Vue.use(VueRouter)

// 2. Define route components 在src/router/index.js中导入子组件
import greeting from "../components/greeting";
import projectlist from "../components/projectlist";
import projectlistNew from "../components/projectlistNew";
import login from "../components/login";
import loginNew from "../components/loginNew";
import HelloWorld from "@/components/HelloWorld";

// 3. Create the router 在src/router/index.js中创建路由:一个routers数组中的一个对象,就是一条路由
const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', component: HelloWorld,name:'hello-world'},
        { path: '/projectlist1', component: projectlist,name:'projectlist1' },
        { path: '/projectlist2', component: projectlistNew,name:'projectlist2' },
        { path: '/login1', component: login,name:'login1' },
        { path: '/login2', component: loginNew,name:'login2' },
        { path: '/greeting', component: greeting,name:'greeting' }
    ]
});
// 4、导出路由
export default router;

main.js file:

//导入vue.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//导入App.vue根组件
import App from './App.vue'
//5.1、导入vue router对象
import router from './router/index'
import loginNew from "@/components/loginNew";
//创建全局组件
Vue.component('login-New',loginNew);
//在导入Vue实例之前,要将element-ui插件加入到Vue中
Vue.use(ElementUI);
Vue.config.productionTip = false


new Vue({
    //5.2、把router挂载到Vue实例中去
  router,
  render: h => h(App),//渲染App根组件
}).$mount('#app')

 App.vue file

Before using routing:
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/jack_li.png">
    <HelloWorld msg="欢迎来到 Vue.js App"/>
    <greeting data_1="这是个app父组件传参给子组件"/>
    <projectlist></projectlist>
    <projectlistNew></projectlistNew>
    <login></login>
    <login-New></login-New>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import greeting from './components/greeting.vue'
import projectlist from "@/components/projectlist";
import projectlistNew from "@/components/projectlistNew";
import login from "@/components/login";
import loginNew from "@/components/loginNew";

export default {
  name: 'App',
  components: {
    HelloWorld,
    greeting,
    projectlist,
    projectlistNew,
    login,
    loginNew
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

img {
  width: 150px;
  height: 150px;
}
</style>

 

 Disadvantage: We need to manually modify the path to jump to different pages

  After using routing:
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/jack_li.png">
    <ul>
      <li>
        <router-link :to="{name:'hello-world'}">菜单一HelloWorld</router-link>
      </li>
      <li>
        <router-link :to="{name:'projectlist1'}">菜单二projectlist</router-link>
      </li>
      <li>
        <router-link :to="{name:'projectlist2'}">菜单三projectlistNew</router-link>
      </li>
      <li>
        <router-link :to="{name:'login1'}">菜单四login</router-link>
      </li>
      <li>
        <router-link :to="{name:'login2'}">菜单五loginNew</router-link>
      </li>
      <li>
        <router-link :to="{name:'greeting',params:{username:'高老庄'}}">菜单六greeting</router-link>
      </li>
      <li>
        <router-link :to="{name:'xibo_test_index'}">菜单七xibo_index</router-link>
      </li>
    </ul>
    <!--    展示路由的页面内容-->
    <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'App',
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

img {
  width: 150px;
  height: 150px;
}
</style>

 

  • Display the routing page content in <router-view></router-view> in the <template> tag of App.vue
    • Disadvantage: You must manually change the route to jump to different pages
    • Optimization: Use <router-link to="routing path"></router-link> in the label of the parent component to jump to the page by clicking on the label.
      • The to attribute defaults to the path value,
        • Disadvantage: If one place changes, two local paths need to be modified.
        • Optimization: You can add the name attribute in the path, and then in the parent component: to="{name:name_value"}

3. Nested routing

In the index.js file,

{
    path: '/login1',
    component: login,
    name: 'login1',
    children: [
        // an empty path will be treated as the default, e.g.
        // components rendered at /parent: Root -> Parent -> Default
        // {path: '', component: login, name: 'login1'},
        //如果加/,则会从根路由开始匹配,http://localhost:8081/login2
        {path: '/login2', component: loginNew, name: 'login2'},
        //如果不加/,则会自动拼接到父路由后面,http://localhost:8081/login1/login2
        {path: 'login2', component: loginNew, name: 'login2'},

4. Query string parameters/path parameters

4.1. In the sub-component, you can obtain the query string parameters through this.$route.query.username ;
methods:{
  //方法一:
  // changeusername:function (){
  //   this.username="dalao"
  // },
  //方法二:推荐使用
  changeusername(){
    this.username="一个没有整容需求的人"
  }
},
created() {
  console.log("实例创建之后,能够获取到this");
  console.log("username为:",this.username);
  this.username=this.$route.query.name;
  this.age=this.$route.query.age;

4.2. Path parameter: on the url (path + ":parameter" in ptah)

Query path parameters, this.$route.params.username

 

路由文件index.js
const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', component: HelloWorld,name:'hello-world'},
        { path: '/projectlist1', component: projectlist,name:'projectlist1' },
        { path: '/projectlist2', component: projectlistNew,name:'projectlist2' },
        { path: '/login1', component: login,name:'login1' },
        { path: '/login2', component: loginNew,name:'login2' },
        //路径参数:在url上(在ptah中路径+":参数")
        { path: '/greeting/:username', component: greeting,name:'greeting' }
    ]
子组件 greeting.vue
created() {
  console.log("实例创建之后,能够获取到this");
  console.log("username为:",this.username);
  this.username=this.$route.query.name;
  this.age=this.$route.query.age;
  this.username=this.$route.params.username;
  // this.age=this.$route.params.age;
},
4.2.1. There is another way to obtain path parameters:

The parameters in the template are written as { {this.$route.params.username}}

<p>username为:{
   
   {this.$route.params.username}}</p>

Then there is no need to write this.username=this.$route.params.username in created()

created() {
    //获取路径参数
// this.username=this.$route.params.username;
    }

The difference between jquery parameter passing and params parameter passing

1. Usage:

As mentioned above, query can be introduced using name or path.

params must be introduced with name, and the received parameters are similar, namely:

this.$route.query.name和

2. Address bar representation:

query:

/login?id=10&name=zs

params:

/login/12/ls

Notice:

The 12 and ls here correspond to /:id/:name;

These two parameters do not need to be written, then they will not be displayed on the address bar;

However, if you refresh the page, the parameters will disappear;

Refresh the page by writing the parameters, and the parameters will not disappear.

 

Passing and receiving parameters in query mode

Pass parameters:

this.$router.push({
        path:'/detail/:id',
        query:{
          id:id
        }
      })

Receive parameters:

this.$route.query.id

Passing and receiving parameters in params mode

Pass parameters:

this.$router.push({
        name:'Detail',
        params:{
          id:id
        }
      })

Receive parameters:

this.$route.params.id

Tips:

When passing parameters via params, push can only be name:'xxxx', not path:'/xxx', because params can only use name to introduce routes. If path is written here, the parameter receiving page will be undefined! ! !

switch route

 

// query通过path切换路由
<router-link :to="{path: 'Detail', query: { id: 1 }}">前往Detail页面</router-link>
// params通过name切换路由
<router-link :to="{name: 'Detail', params: { id: 1 }}">前往Detail页面</router-link>

Simply put, query is equivalent to a get request. When the page jumps, you can see the request parameters in the address bar. The page will not disappear when the browser refreshes. Params is equivalent to a post request. The parameters will not be displayed in the address bar when the browser refreshes. The page disappears.

Guess you like

Origin blog.csdn.net/weixin_43569834/article/details/132596735