tnblog
首页
视频
资源
登录
这世间真的有很美的爱情,也有很温柔善良的女孩纸。
排名
4
文章
473
粉丝
3
评论
2
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

vue2教程中路由项目分析

4933人阅读 2020/6/25 17:32 总访问:280999 评论:0 收藏:0 手机
分类: 前端

main.js
webpack.config.js 中的 entry 属性告诉我们项目以 main.js 作为入口。

main.js 首先引入 vue 和 routes,vue 不多说,routes 是路径参数。

import 和 export 困扰了我很久,因为用 script 标签引入 json 对象很方便,但在 node 环境开发中就很麻烦,所以理解它俩花了我很多功夫和时间。

import 用来引入函数、对象或者模块,export 用来输出函数、对象或者模块,它们目前只能在 babel 等转换器中实现,浏览器不支持。

然后创建实例,el 挂载 #app,currentRoute 由 window.location.pathname 得到 ‘/‘。

computed 属性中的 ViewComponent 函数计算当前应该渲染的组件,由 routes[this.currentRoute] 得到组件名称。如果存在该组件,则加载该组件,如果不存在,则加载 404.vue 组件。

目前加载的是 Home.vue 组件。

Home.vue
home.vue 是主页的组件,模板是

  1. <template>
  2. <main-layout>
  3. <p>Welcome home</p>
  4. </main-layout>
  5. </template>

结构与 About.vue 和 404.vue 类似。然后引入 MainLayout,来自 Main.vue 组件。

这里有个 slot 的知识点。

除非子组件模板包含至少一个 插口,否则父组件的内容将会被丢弃。当子组件模板只有一个没有属性的 slot 时,父组件整个内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身。

父组件 Home.vue 的

Welcome home

会插入到 Main.vue 中所在的位置。

当 Main.vue 作为子组件渲染完毕后,Home.vue 作为对象export给父组件

Main.vue
main.vue 的作用是页面的布局,模板是

  1. <template>
  2. <div class="container">
  3. <ul>
  4. <li>
  5. <v-link href="/">Home</v-link>
  6. <v-link href="/about">About</v-link>
  7. </li>
  8. </ul>
  9. <slot></slot>
  10. </div>
  11. </template>

v-link,这是这个案例的核心。

然后引入VLink。

当 VLink.vue 作为子组件渲染完毕后,Main.vue 作为对象 export 给父组件Home.vue

Vlink.vue
VLink.vue组件渲染链接,模板是

  1. <template>
  2. <a
  3. v-bind:href="href"
  4. v-bind:class="{ active: isActive }"
  5. v-on:click="go"
  6. >
  7. <slot></slot>
  8. </a>
  9. </template>

在 js 代码段引入 routes 得到地址参数,v-bind:href=”href” 绑定链接地址,第一个 href 需要 props 的声明,否则出现未定义错误,这里还用到了类型检测。

v-bind:href 的值来自 Main.vue 中的 Home的”/“。

在 Main.vue 中有两个 v-link 组件,渲染第二个 v-link 时,v-bind:href 的值是”/about”。
slot插值的算法参看Home.vue

v-bind:class 绑定类,这影响到链接的样式。

computed 属性计算 isactive 的值,如果和 this.$root.currentRoute 的值相同,class 显示 isactive,否则不显示。

v-on:click绑定鼠标点击事件,点击后运行go函数。

event.preventDefault()防止默认行为,这里是页面跳转。

this.$root.currentRoute = this.href变更组件路径,行为反馈到main.js的ViewComponent (),实例中的 render 重新渲染组件。

window.history.pushState()是浏览器的历史记录API,是HTML5的新API。

history.pushState()

原文地址:
https://segmentfault.com/a/1190000008559505

评价