Vue路由

1.什么是路由?

一个路由就是一种映射关心(key-value)

key为路径,value可能为function或componen

2.基本路由

1.安装vue-router,命令 npm i vue-router

2.应用插件 Vue.use(VueRouter)

3.编写router配置项

//index.js界面
import VueRouter from 'vue-router'       //引入VueRouter
import About from '@/components/About'   //路由插件
import Home from '@/components/Home'     //路由插件

export default new VueRouter({
    routes: [
        {
            path:'/About',
            component:About
        },
        {
            path:'/Home',
            component:Home
        }
    ]
})
//home界面
<template>
    <div>
        <h1>我是home组件</h1>
    </div>
</template>

<script>
export default {
    name:'Home',
    mounted(){
        console.log("home组件即将被挂载");
    },
beforeDestroy() {
       console.log("about组件即将被销毁");
    }
}
</script>

<style>

</style>
//about界面
<template>
    <div class="box1">
        <h1>我是about组件</h1>
    </div>
</template>

<script>
export default {
    name:'About',
    mounted(){
        console.log("about组件即将被挂载");
    }
beforeDestroy() {
       console.log("home组件即将被销毁");
    }
}
</script>

<style scoped>
    .box1{
        width: 200px;
        height: 200px;
    }
</style>
//需要操作的界面
<template>
  <div>
   <router-link to="/About">About组件</router-link>
   <router-link to="/Home">Home组件</router-link>
   <!-- 展示区域 -->
   <div class="box1">
        <router-view></router-view>
   </div>
   
  </div>
</template>

<script>
export default {
    name:"MyDay",
    data() {
        return {
            
        }
    },
    methods:{

    }
}
</script>

<style>
    .box1{
        width: 500px;
        height: 500px;
        border: 1px #a1a1a1 solid;
    }
</style>
1.通过切换组件,就是不断销毁旧组件,需要的时候挂载新组件

所以当点击Home组件时,控制台会输出:

about组件即将被销毁

home组件即将被挂载

2.每个组件都有自己的$router属性,里面存储着自己路由信息
3.整个应用只有一个router,可以通过组件的$router属性获取到

注:<router-link></routerr-link>浏览器会被替换为a标签

3.多级路由

配置路由规则,需要使用children配置

//index.js界面
import VueRouter from 'vue-router'       //引入VueRouter
import About from '@/components/About'   //路由插件
import Home from '@/components/Home'     //路由插件
import hos from '@/components/hos.vue'   //路由插件
import hs from '@/components/hs.vue'     //路由插件

export default new VueRouter({
    routes: [
        {
            path:'/About',
            component:About
        },
        {
            path:'/Home',
            component:Home,
            children:[
                {
                    path:'Hs',
                    component:hs
                },
                {
                    path:'Hos',
                    component:hos
                }
            ]
        }
    ]
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值