当前位置: 移动技术网 > IT编程>网页制作>CSS > vue路由搭建教程

vue路由搭建教程

2019年04月19日  | 移动技术网IT编程  | 我要评论

安装vue-router

cnpm install vue-router

src目录下添加content.vue,date.vue和route.js

//date.vue

{{name}}

<script> export default { name:'date', computed:{ name(){ return 'date' } }, methods:{ }, mounted(){ } } </script>*{margin:0;padding:0;} p{margin:10px 0;background:#eee;}

//content.vue

{{name}}

<script> export default { name:'content', computed:{ name(){ return 'content' } }, methods:{ }, mounted(){ } } </script>*{margin:0;padding:0;} p{margin:10px 0;background:#eee;}

//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结构改成

content date

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链接改成需要的

date

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
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网