zoukankan      html  css  js  c++  java
  • Vue Router的官方示例改造

      基于Vue Router 2018年8月的官方文档示例,改造一下,通过一个最简单的例子,解决很多初学者的一个困惑。

      首先是官方文档示例代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <div id="app">
          <h1>Hello App!</h1>
          <p>
    
            <router-link to="/foo">Go to Foo</router-link>
            <router-link to="/bar">Go to Bar</router-link>
          </p>
    
          <router-view></router-view>
        </div>
        <script src="vue.js"></script>
        <script src="vue-router.js"></script>
        <script>
            const Foo = { template: '<div>foo</div>' }
            const Bar = { template: '<div>bar</div>' }
    
            const routes = [
              { path: '/foo', component: Foo },
              { path: '/bar', component: Bar }
            ]
    
            const router = new VueRouter({
              routes
            })
    
            const app = new Vue({
              router
            }).$mount('#app')
        </script>
    </body>
    </html>

      效果如下

      但此时,你点击子组件路由链接,会发现进入新路由后,页面外层的'Hello App!'等文字等仍然都在。不想要这些东西该怎么办?

      其实这个很好办,先看咱们的新代码

      

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <div id="app">
          <router-view></router-view>
        </div>
    
        <script src="vue.js"></script>
        <script src="vue-router.js"></script>
        <script>
    
            const Index = { template: '<div>index <router-link to="/foo">Go to Foo</router-link></div>' }
            const Foo = { template: '<div>foo <router-link to="/bar">Go to Bar</router-link></div>' }
            const Bar = { template: '<div>bar</div>' }
    
            const routes = [
              { path: '/', component: Index },
              { path: '/foo', component: Foo },
              { path: '/bar', component: Bar }
            ]
    
            const router = new VueRouter({
              routes
            })
    
            const app = new Vue({
              router
            }).$mount('#app')
        </script>
    </body>
    </html>

    效果如下

      关键点就是在写路由对象的时候,多写一个‘/’路径,这个路径对应咱们的首页组件,在这个首页组件里写跳转路由链接,另外就是在Vue示例挂载DOM里(这里是#app),我们只写一个<router-view></router-view>,用来渲染各个路由组件,

    这样首页内容渲染的是首页组件的,其他页面也不会有多余的‘Hello App’显示在路由组件渲染后的页面上了。

  • 相关阅读:
    抛弃【 LIMIT O,N 】,换种方法查询分页
    在美国,男 / 女卫生间(厕所)的正确称呼为什么?请用英语写出答案。
    CSS3 选择器
    使用Git将项目上传到github
    Elasticsearch 的 Update更新
    elasticsearch 基本用法
    elasticsearch 基础性操作
    elasticsearch 插入数据
    elasticsearch 安装和部署
    关于httpclient 请求https (如何绕过证书验证)
  • 原文地址:https://www.cnblogs.com/zhansu/p/9491288.html
Copyright © 2011-2022 走看看