vue路由搭建

接上一篇搭建好结构的基础上,安装vue-router

cnpm install vue-router

src目录下添加Content.vue,Date.vue和route.js

//Date.vue

<template>
    <div>
        <p>{{name}}</p>    
    </div>
</template>
<script>
export default {
    name:'date',
    computed:{
        name(){
            return 'date'
        }
    },
    methods:{

    },
    mounted(){
        
    }
}
</script>
<style>
    *{margin:0;padding:0;}
    p{margin:10px 0;background:#eee;}
</style>

 

//Content.vue

<template>
    <div>
        <p>{{name}}</p>
    </div>
</template>
<script>
export default {
    name:'Content',
    computed:{
        name(){
            return 'content'
        }
    },
    methods:{

    },
    mounted(){
        
    }
}
</script>
<style>
    *{margin:0;padding:0;}
    p{margin:10px 0;background:#eee;}
</style>

//route.js

import Vue from 'vue'
import Router from 'vue-router'
import Da from './Date.vue'
import Content from './Content.vue'
 
Vue.use(Router)
 
export default new Router({
  routes: [
    {
      path: '/content',
      component: Content
    },
    {
      path: '/date',
      component: Da
    }
  ]
})

App.vue template结构改成

<template>
	<div>
		<router-link to="/content">content</router-link>
		<router-link to="/date">date</router-link>
		<router-view></router-view>
	</div>  
</template>

main.js引入route.js,并注入模块中

//Main.js
import Vue from 'vue';
import App from './App.vue';
import router from './route'

new Vue({
  el:'#app',
  router,
  components: {App},
  render: h => h(App),
  mounted:function(){console.log('hello world')}
})

至此简单的路由功能已经搭建完成。组件中可以通过this.$router和this.$route访问路由器和当前路由。

使用动态路由,例如date/xiaogang,只需要将router-link链接改成需要的

<router-link to="/date/xiaogang">date</router-link>

route.js

{
    path: '/date/:name',
    component: Da
}

Date.vue,使用this.$route.params.name就能获取到对应数据

computed:{
    name(){
        return this.$route.params.name
    }
},

关于重定向,只要设置redirect,默认跳转content组件

{
    path: '/',
    redirect:'/content',
    component: Content
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值