【VUE】vue.js中的路由router

前言:

本章节我们将为大家介绍 Vue.js 路由。

Vue.js 路由允许我们通过不同的 URL 访问不同的内容。

通过 Vue.js 可以实现多视图的单页Web应用(single page web application,SPA)。

Vue.js 路由需要载入 vue-router 库

中文文档地址:vue-router文档

一、安装router:

1、直接下载 / CDN

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

2、CNPM

推荐使用淘宝镜像:

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

二、简单路由

  1. 创建路由规则文件

    1. 路径:src/router/index.js
  2. 将router挂载到vue实例

    1. main.js文件中的注释5.2
  3. 路由参数类型

    1. 路径参数 (params只能通过name来引入路由,path会undefined)
    2. 查询字符串参数 (query可以通过name或path来引入路由)
  4. 路由跳转

    1. 使用router-link
    2. to属性可以为path路径、命名路由以及路径参数和查询字符串参数
  5. element ui的案例 

步骤:

1、将example里的。。。粘贴到src/router/index.js里

路由的创建站们放到单独的文件里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文件:

//导入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文件

使用路由前:
<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>

 

 不足:我们需要手动的修改路径才能跳转到不同页面

  使用路由后:
<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>

 

  • 在App.vue的<template>标签内中<router-view></router-view>展示路由的页面内容
    • 不足:必须要手动改变路由才能跳转到不同页面
    • 优化:在父组件的标签内使用<router-link to="路由路径"></router-link>可以达到点击标签就可以跳转页面
      • to属性默认为path路径值,
        • 不足:如果一个地方改变,就要修改2个地方路径
        • 优化:可以在path中添加name属性,然后在父组件中:to="{name:name_value"}

三、嵌套路由

在index.js文件中,

{
    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.1、在子组件中可以通过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、路径参数:在url上(在ptah中路径+":参数")

查询路径参数,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、还有一种方法获取路径参数 就是:

在template里参数写成{ {this.$route.params.username}}

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

然后在created()就不用写this.username=this.$route.params.username

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

jquery传参和params传参的区别

1、用法上:

上文已经提到query可以用name或path来引入

params必需要用name来引入,接收参数都是类似的,分别是:

this.$route.query.name和

2、地址栏表现形式上:

query:

/login?id=10&name=zs

params:

/login/12/ls

注意:

这里的12和ls对应的是/:id/:name;

这两个参数可以不写,那么就不会再地址栏上显示;

不过刷新页面,参数会消失;

写上参数刷新页面,参数不会消失。

query方式传参和接收参数

传参:

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

接收参数:

this.$route.query.id

params方式传参和接收参数

传参:

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

接收参数:

this.$route.params.id

Tips:

params传参,push里面只能是 name:‘xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!

切换路由

// 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>

简单说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,浏览器刷新页面不会消失,而params相当于post请求,参数不会在地址栏中显示,浏览器刷新页面后消失。

猜你喜欢

转载自blog.csdn.net/weixin_43569834/article/details/132596735