Vue 路由使用

简单的路由使用

1. 安装(注意,vue2最高只能使用3版本,vue3才能使用4以及以上的版本,vue2使用4以上版本会报错)
npm i vue-router@3 // 指定3版本

2. 在src下创建router文件夹,在index.js内定义好,代码如下:

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router';
import SchoolName from '../components/SchoolName';
import StudentName from '../components/StudentName';

// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/schoolName',
            component: SchoolName
        },
        {
            path: '/studentName',
            component: StudentName
        }
    ]
});

export default router;

3. 在main.js内使用

/**
 * 该文件是整个项目的入口文件
 */
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import router from './router';
import store from './store';

// VueRouter是插件,必须写Vue.use
Vue.use(VueRouter);

// 关闭vue的生产提示
Vue.config.productionTip = false
// 创建vue实例对象
new Vue({
  // 完成了功能:将App组件放入容器中
  render: h => h(App),
  store,
  router,
  beforeCreate () {
    Vue.prototype.$bus = this;
  }
}).$mount('#app')

4. 使用完后可以去组件内体验,代码如下:

<template>
    <div>
        <!-- <SchoolName />
        <StudentName /> -->

        <!-- 路由 -->
        <!-- active-class激活时显示的高亮 -->
        <router-link active-class="active" to="/schoolName">SchoolName</router-link>
        <router-link active-class="active" to="/studentName">StudentName</router-link>

        <!-- 指定路由呈现位置 -->
        <router-view />
    </div>
</template>

<script>
    import SchoolName from './components/SchoolName';
    import StudentName from './components/StudentName';

    export default {
        name: 'App',
        data () {
            return {
                msg: '好忙'
            }
        },
        methods: {},
        components: {SchoolName, StudentName}
    }
</script>

<style>
    .active {
        color: red;
    }
</style>

嵌套路由

1. router文件夹下的index.js

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router';
import SchoolName from '../components/SchoolName';
import StudentName from '../components/StudentName';
import Child from '../components/Child';
import Some from '../components/Some';

// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/schoolName',
            component: SchoolName,
            children: [
                {
                    path: 'child',
                    component: Child,
                },
                {
                    path: 'some',
                    component: Some,
                }
            ]
        },
        {
            path: '/studentName',
            component: StudentName
        }
    ]
});

export default router;

2. SchoolName组件内使用嵌套路由

<template>
  <div>
      路由1

      <hr />
      <router-link active-class="active" to="/schoolName/child">路由child</router-link>
      <router-link active-class="active" to="/schoolName/some">路由some</router-link>

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

<script>
    export default {
        name: 'SchoolName',
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            handleClick() {
                this.isShow = !this.isShow
            }
        }
    }
</script>



命名路由(优点:简化路由路径)

router.js:
// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router';
import SchoolName from '../components/SchoolName';
import StudentName from '../components/StudentName';
import Child from '../components/Child';
import Some from '../components/Some';

// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/schoolName',
            component: SchoolName,
            children: [
                {
                    name: 'child', // 随机取名,最好与path保持一致
                    path: 'child',
                    component: Child,
                },
                {
                    path: 'some',
                    component: Some,
                }
            ]
        },
        {
            path: '/studentName',
            component: StudentName
        }
    ]
});

export default router;

组件:
<template>
  <div>
      路由1

      <hr />
      <!-- 写法一,不推荐, 模板字符串写法 :to="`/schoolName/child?id=${id}`" -->
      <!-- <router-link active-class="active" to="/schoolName/child?id=111">路由child</router-link> -->

      <!-- 写法二,对象写法,推荐 -->
      <!-- <router-link active-class="active" to="/schoolName/child"> -->
      <router-link active-class="active" 
        :to="{
          name: 'child',
          query: {id: 111}
        }"
      >
        路由child 
      </router-link>
      <router-link active-class="active" to="/schoolName/some">路由some</router-link>

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

<script>
    export default {
        name: 'SchoolName',
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            handleClick() {
                this.isShow = !this.isShow
            }
        }
    }
</script>

路由传参(query)

父组件路由跳转:

<template>
  <div>
      路由1

      <hr />
      <!-- 写法一,不推荐, 模板字符串写法 :to="`/schoolName/child?id=${id}`" -->
      <!-- <router-link active-class="active" to="/schoolName/child?id=111">路由child</router-link> -->

      <!-- 写法二,对象写法,推荐 -->
      <!-- <router-link active-class="active" to="/schoolName/child"> -->
      <router-link active-class="active" 
        :to="{
          path: '/schoolName/child',
          query: {id: 111}
        }"
      >
        路由child 
      </router-link>
      <router-link active-class="active" to="/schoolName/some">路由some</router-link>

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

<script>
    export default {
        name: 'SchoolName',
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            handleClick() {
                this.isShow = !this.isShow
            }
        }
    }
</script>


子组件接收:

<template>
  <div>
      路由3
  </div>
</template>

<script>
    export default {
        name: 'Child',
        data() {
            return {
            }
        },
        mounted() {
          // 获取路由传参
          console.log(this.$route.query.id);
        }
    }
</script>



 路由传参(params)

router.js:
// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router';
import SchoolName from '../components/SchoolName';
import StudentName from '../components/StudentName';
import Child from '../components/Child';
import Some from '../components/Some';

// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/schoolName',
            component: SchoolName,
            children: [
                {
                    name: 'child', // 随机取名,最好与path保持一致
                    path: 'child/:id/:title', // 使用params需要在path路由后面占位
                    component: Child,
                },
                {
                    path: 'some',
                    component: Some,
                }
            ]
        },
        {
            path: '/studentName',
            component: StudentName
        }
    ]
});

export default router;

组件:
<template>
  <div>
      路由1

      <hr />
      <!-- 写法一,路由的path必须写成: 'child/:id/:title', // 使用params需要在path路由后面占位 -->
      <!-- <router-link active-class="active" to="/schoolName/child/111/666">路由child</router-link> -->

      <!-- 写法二,对象写法,推荐,路由可以不占位也能生效,建议占位 -->
      <router-link active-class="active" 
        :to="{
          // 注意,使用对象写法必须使用name,使用path会报错
          name: 'child',
          params: {id: 111, title: 666}
        }"
      >
        路由child 
      </router-link>
      <router-link active-class="active" to="/schoolName/some">路由some</router-link>

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

<script>
    export default {
        name: 'SchoolName',
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            handleClick() {
                this.isShow = !this.isShow
            }
        }
    }
</script>

路由的props配置

这里的案例是使用params和query传参,配置好后也用props接收
通用子组件写法:
<template>
  <div>
      路由3
      {{id}}
      {{title}}
  </div>
</template>

<script>
    export default {
        name: 'Child',
        props: ['id', 'title'], // 路由配置好布尔值后,这里使用props接收
        data() {
            return {
            }
        },
        mounted() {
          // 获取路由传参
          console.log(this.$route);
        }
    }
</script>

---------------------------------------------------------
使用params写法:

router.js
// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router';
import SchoolName from '../components/SchoolName';
import StudentName from '../components/StudentName';
import Child from '../components/Child';
import Some from '../components/Some';

// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/schoolName',
            component: SchoolName,
            children: [
                {
                    name: 'child', // 随机取名,最好与path保持一致
                    path: 'child/:id/:title', // 使用params需要在path路由后面占位
                    component: Child,
                    // props的三种写法
                    // 1. 值为对象,该对象的所有key-value都会以props传给Child组件, 很少使用,因为值都是固定不变的
                    // props: {id: 11, title: 666}
                    // 2. 布尔值写法,若布尔值为真,就会把该组件收到的所有params参数,以props传给Child组件,使用params传参时使用
                    props: true
                    // 3. 值为函数, 使用query传参时使用
                    // props($router) {
                    //     return {id: $router.query.id, title: $router.query.title}
                    // }
                },
                {
                    path: 'some',
                    component: Some,
                }
            ]
        },
        {
            path: '/studentName',
            component: StudentName
        }
    ]
});

export default router;

父组件:
<template>
  <div>
      路由1

      <hr />
      <!-- 写法一,不推荐 -->
      <!-- <router-link active-class="active" to="/schoolName/child/111/666">路由child</router-link> -->

      <!-- 写法二,对象写法,推荐 -->
      <router-link active-class="active" 
        :to="{
          // 注意,使用对象写法必须使用name,使用path会报错
          name: 'child',
          params: {id: 111, title: 666}
        }"
      >
        路由child 
      </router-link>
      <router-link active-class="active" to="/schoolName/some">路由some</router-link>

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

<script>
    export default {
        name: 'SchoolName',
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            handleClick() {
                this.isShow = !this.isShow
            }
        }
    }
</script>




-----------------------------------------------------------------------------------------
使用query写法:
router.js:
// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router';
import SchoolName from '../components/SchoolName';
import StudentName from '../components/StudentName';
import Child from '../components/Child';
import Some from '../components/Some';

// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/schoolName',
            component: SchoolName,
            children: [
                {
                    name: 'child', // 随机取名,最好与path保持一致
                    path: 'child', // 使用params需要在path路由后面占位
                    component: Child,
                    // props的三种写法
                    // 1. 值为对象,该对象的所有key-value都会以props传给Child组件, 很少使用,因为值都是固定不变的
                    // props: {id: 11, title: 666}
                    // 2. 布尔值写法,若布尔值为真,就会把该组件收到的所有params参数,以props传给Child组件,使用params传参时使用
                    // props: true
                    // 3. 值为函数, 使用query传参时使用
                    props($router) {
                        return {id: $router.query.id, title: $router.query.title}
                    }
                },
                {
                    path: 'some',
                    component: Some,
                }
            ]
        },
        {
            path: '/studentName',
            component: StudentName
        }
    ]
});

export default router;

父组件:
<template>
  <div>
      路由1

      <hr />
      <!-- 写法一,不推荐 -->
      <!-- <router-link active-class="active" to="/schoolName/child/111/666">路由child</router-link> -->

      <!-- 写法二,对象写法,推荐 -->
      <router-link active-class="active" 
        :to="{
          // 注意,使用对象写法必须使用name,使用path会报错
          path: '/schoolName/child',
          query: {id: 111, title: 666}
        }"
      >
        路由child 
      </router-link>
      <router-link active-class="active" to="/schoolName/some">路由some</router-link>

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

<script>
    export default {
        name: 'SchoolName',
        data() {
            return {
                isShow: true
            }
        },
        methods: {
            handleClick() {
                this.isShow = !this.isShow
            }
        }
    }
</script>

router-link的replace属性

1. 控制路由跳转时操作浏览器历史记录的模式
2. 浏览器的历史记录有两种写入方式,分别是replace和push,push是追加历史记录,replace是替换当前记录,路由跳转的时候默认是push
3. 如何开启replace模式:<router-link replace>路由</router-link>

编程式路由导航

<template>
  <div>
    路由1

    <hr />
    <!-- 写法一,不推荐 -->
    <!-- <router-link active-class="active" to="/schoolName/child/111/666">路由child</router-link> -->

    <!-- 写法二,对象写法,推荐 -->
    <!-- <router-link active-class="active" 
        :to="{
          // 注意,使用对象写法必须使用name,使用path会报错
          name: 'child',
          params: {id: 111, title: 666}
        }"
      >
        路由child 
      </router-link> -->
    <!-- <router-link active-class="active" to="/schoolName/some">路由some</router-link> -->

    <button @click="handlePush">push跳转按钮</button>
    <button @click="handleReplace">replace跳转按钮</button>
    <button @click="handleForward">前进</button>
    <button @click="handleBack">后退</button>
    <button @click="handleGo">go</button>

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

<script>
export default {
  name: 'SchoolName',
  data() {
    return {
    }
  },
  mounted() {
    console.log(this.$router);
  },
  methods: {
    handlePush() {
      // router用法与to的对象用法完全一致
      this.$router.push({
        name: 'child',
        params: { id: 111, title: 666 }
      })
    },
    handleReplace() {
      // router用法与to的对象用法完全一致
      this.$router.replace({
        name: 'child',
        params: { id: 111, title: 666 }
      })
    },
    handleForward() {
      this.$router.forward()
    },
    handleBack() {
      this.$router.back()
    },
    handleGo() {
      this.$router.go(1) // 正数代表前进N个页面跳转,负数代表后退
    }
  }
}
</script>

缓存路由组件

1. 作用:让不展示的路由组件保持挂载,不被销毁
2. 具体编码:
// include表示哪些路由组件需要缓存起来,命名使用的是组件名name
// 单个写法
<keep-alive include="About">
    <router-view></router-view>
</keep-alive>

// 多个缓存写法
<keep-alive :include="['About', 'News']">
    <router-view></router-view>
</keep-alive>



两个新的生命周期(路由特有的,顺便提一下除了正常的八个生命钩子还有三个钩子,这两个加上this.$nextTick)

作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态

<template>
  <div>
    路由3
    {{ id }}
    {{ title }}
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: ['id', 'title'], // 路由配置好布尔值后,这里使用props接收
  data() {
    return {
    }
  },
  activated() {
    console.log('激活');
  },
  deactivated() {
    console.log('失活');
  }
}
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值