vue-cli教程(二) 路由

vue路由使用vue-router,在教程一中已经安装,而且有相关示例html

vue-router官方文档:https://router.vuejs.org/zh-cn/ vue

   主页面的App.vue中的<vue-router></vue-router>保存最上级的indexwebpack

    子组件的vue中的<vue-router></vue-router>包含的是children的信息web

routes:[
    {
        path:"/index",
        name:"mycomponent",
        component:MyComponent,
        children:[
            {
                path:"index1",    //不要加斜杠
                name:"index1",
                component:MyComponent2
            }
        ]
    }
]

路由的访问:

    html标签:<a href="#/index/index1"></a>vue-router

    或 <router-link to='/index/index1'></router-link>npm

    js方法:app

        window.location.href='#/index/index1' ,函数

        或:this.$router.push({path:'/index/index1'}) ......ui

  全局监听路由变化:

        watch:{this

             $route:function(new,old){

                console.log(new,old);

            }

        }

        前置路由,后置路由,生命周期函数,文档里面都有,请参考文档

注意:

        vue中路由存在两个值 this.$router 和this.$route 至于为啥存在两个我也不清楚,求大神解释^-^

        this.$router 主要是执行动做的时候调用,如 跳转,前进,后退

        this.$route  主要为获取参数,如 this.$route.hash,this.$route.match等

 

 

若是没有使用,或者教程一中一不当心,没安装vue-router,就进行如下操做:

    cnpm install vue-router --save

路由的使用:

    除了教程一中的系统默认的方法加载路由,还有其余的方法

    1.在components里面写上本身的组件MyComponent.vue

<template>
    <div>
        这个是个人组件  ,我随便写的
    </div>
</template>
<script>
    export default{
        name:"MyComponent"  //不要也行
    }
</script>

    2.建立route的文件夹,写上index.js,贴上如下代码

import Vue from 'vue'
import Router from 'vue-router'
import MyComponent from "../components/MyComponent.vue"
Vue.use(Router);

export default new Router({
    routes:[
        {
            path:"/index",
            name:"mycomponent",
            component:MyComponent
        }
    ]
})

3.main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App.vue'
import router from './route/index.js'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    template: '<App/>',
    components: { App },
    router:router                  //若是键名称和import的模块名称同样也叫router,键能够不写。换名字的必定要写router:***
})

4.App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png" />
    <hello></hello>
    <router-view></router-view>  <!---->
  </div>
</template>

<script>
import Hello from './components/Hello'

export default {
  name: 'app',
  components: {
    Hello
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
相关文章
相关标签/搜索