美文网首页
Vue路由和路由嵌套

Vue路由和路由嵌套

作者: 凌康ACG | 来源:发表于2019-08-17 18:05 被阅读0次

    效果图如下:


    GIF.gif

    1、创建好项目环境

    可参考上篇https://www.jianshu.com/p/98fb7f0a45b7

    修改配置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'
    import router from './router'
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      components: { App },
      router,
      template: '<App/>'
    })
    

    加入了路由install一下:
    npm install --save vue-router

    修改App.vue:

    <template>
      <div id="app">
        <!--首页路由-->
        <router-view/>
      </div>
    </template>
    
    <script>
      import main from './views/main'
    
      export default {
        name: 'App',
        components: {
          main
        }
      }
    </script>
    
    <style>
    
    </style>
    

    2、创建视图和模板

    创建src/views文件夹,在views下创建main.vue、page1.vue、page2.vue

    main.vue:

    <template>
      <div>
        <div style="float: left;width: 250px;height: 400px;border-right: 2px solid red;">
          左边内容:
          <br><br>
          <router-link to="/page1">page1</router-link>
          <br><br>
          <router-link to="/page2">page2</router-link>
        </div>
        <div style="float: left;width: 400px;height: 400px;margin-left: 10px;">
          右边内容:<br>
          <!--在这里路由页面-->
          <router-view/>
        </div>
      </div>
    </template>
    
    <script>
      export default {
        name: "main"
      }
    </script>
    
    <style scoped>
    
    </style>
    

    page1.vue:

    <template>
      <div>
        page1内容
      </div>
    </template>
    
    <script>
      export default {
        name: "page1"
      }
    </script>
    
    <style scoped>
    
    </style>
    

    page2.vue:

    <template>
      <div>
        page2内容,page2!
      </div>
    </template>
    
    <script>
      export default {
        name: "page1"
      }
    </script>
    
    <style scoped>
    
    </style>
    

    3、在src下创建router/index.js

    import Vue from 'vue'
    import Router from 'vue-router'
    import main from '@/views/main'
    
    Vue.use(Router)
    
    export default new Router({
      routes: [
        {
          //主页
          path: '/',
          name: 'main',
          component: main,
          children: [
            {
              path: '/page1',
              name: 'page1',
              component: () => import('../views/page1')
            }, {
              path: '/page2',
              name: 'page2',
              component: () => import('../views/page2')
            }
          ]
        }
      ]
    })
    

    项目代码:gitee码云
    项目目录:

    image.png

    相关文章

      网友评论

          本文标题:Vue路由和路由嵌套

          本文链接:https://www.haomeiwen.com/subject/tpuksctx.html