router基础

118 阅读1分钟

配置index:

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/Childa',
    name: 'Childa',
    component: () => import('../views/ChildA.vue'),
    beforeEnter: (go, from, next) => {
      console.log(go)
      console.log(from)
      next()
    }
  },
  {
    path: '/Childb/:id',
    name: 'Childb',
    props:true,
    component: () => import('../views/ChildB.vue'),
  }
]

const router = new VueRouter({
  routes
})
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

router.beforeEach((to,from,next)=>{
  console.log(to)
  console.log(from)
  next()
})
router.afterEach((a,b)=>{
  console.log(a)
  console.log(b)
})
复制代码

配置app主页

<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>|
      <router-link to="/childa?name=zhangsan">ChildA</router-link>|
      <router-link to="/childb/1">ChildB</router-link>
      <button @click="jumpR">跳转</button>
    </nav>
    <router-view />
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    jumpR() {
      this.$router.push("/about");
    },
  },
};
</script>
复制代码

配置子页面

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'HomeView',
  components: {
    HelloWorld
  }
}
</script>

复制代码
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <button @click="backH">返回主页面</button>
  </div>
</template>
<script>
export default {
  methods: {
    backH(){
      this.$router.push('/')
    }
  }
}
</script>

复制代码
<template>
<div>
    <h1>{{msg}}</h1>
   
</div> 
</template>

<script>
export default {
    data:function(){
        return{
            msg:''
        } 
    },
    created(){
        if(this.$route.query.name=='zhangsan'){
            this.msg = '欢迎用户张三登陆'
        }
    }
}
</script>

<style>

</style>
复制代码
<template>
 <div>
    <h1>{{msg}}</h1>    
</div> 
</template>

<script>
export default {
    props:['id'],
    data() {
        return {
            msg:'111'
        }
    },
    created(){
        if(this.$route.params.id=='1'){
            this.msg = '1号房间'
        }
    }
}
</script>

<style>

</style>