Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VueJS 全家桶 #111

Open
coconilu opened this issue Nov 6, 2018 · 0 comments
Open

VueJS 全家桶 #111

coconilu opened this issue Nov 6, 2018 · 0 comments

Comments

@coconilu
Copy link
Owner

coconilu commented Nov 6, 2018

Vuex

在Vue里,每个组件都可以拥有、维护自己的状态。

但是在大型应用里,组件间往往需要共享一些数据,需要把这些共享的数据提取独立出来。

Vuex是专门为 Vue.js 设计的状态管理库——类Flux状态管理方案。

Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。

关联到Vue

  1. 注册Vuex,Vue.use(Vuex)
  2. 实例化一个 Vuex
  3. 传给根Vue的options里的store

组成

  1. State,状态存储
  2. Getters,派生新的状态
  3. Mutations,变更状态的唯一方法
  4. Actions,可以包含异步操作,通过提交mutation变更状态
  5. Modules,模块化

API

store为Vuex的实例

getter:
store.getters.foo

mutation:
store.commit('foo', payload)

action:
store.dispatch('foo', payload)

Vue-Router

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。

基本用法

  1. 首先需要注册组件和路由的关系
Vue.use(VueRouter)

new Router({
  routes: [{path: '/foo', name: 'foo', component: Foo}]
})

// 传给根Vue的options里的router
  1. 设置路由出口,使用<router-view></router-view>

  2. 切换路由渲染的组件,使用<router-link to="/foo">Go to Foo</router-link>

路由的特别功能

  1. 路由是可以嵌套的
  2. 可以通过命名来区分渲染的组件
  3. 路由还可以传递组件的参数
  4. 路由懒加载
  5. 路由过渡动效——<transition></transition>
  6. 导航守卫:全局守卫、路由守卫、组件守卫
完整的导航解析流程:

1. 导航被触发。
2. 在失活的组件里调用离开守卫。
3. 调用全局的 beforeEach 守卫。
4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
5. 在路由配置里调用 beforeEnter。
6. 解析异步路由组件。
7. 在被激活的组件里调用 beforeRouteEnter。
8. 调用全局的 beforeResolve 守卫 (2.5+)。
9. 导航被确认。
10. 调用全局的 afterEach 钩子。
11. 触发 DOM 更新。
12. 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。

API

构建选项:
routes,路由信息对象
mode,路由模式,"hash"(浏览器环境) | "history" | "abstract"(Node.js 环境)
base,基路径
linkActiveClass,全局配置默认“激活 class 类名”
linkExactActiveClass
scrollBehavior,滚动行为,这个功能只在支持 history.pushState 的浏览器中可用
parseQuery / stringifyQuery,提供自定义查询字符串的解析/反解析函数
fallback,当浏览器不支持 history.pushState 控制路由是否应该回退到 hash 模式。默认值为 true

实例属性:
router.app,配置了 router  Vue 根实例
router.mode,路由使用的模式
router.currentRoute,当前路由对应的路由信息对象

实例方法:
router.beforeEach
router.beforeResolve
router.afterEach
router.push(location, onComplete?, onAbort?),向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL
router.replace(location, onComplete?, onAbort?),替换掉当前的 history 记录
router.go(n),类似 window.history.go(n)
router.back
router.forward
router.getMatchedComponents
router.resolve
router.addRoutes,动态添加更多的路由规则
router.onReady,该方法把一个回调排队,在路由完成初始导航时调用,这意味着它可以解析所有的异步进入钩子和路由初始化相关联的异步组件
router.onError,注册一个回调,该回调会在路由导航过程中出错时被调用

参考

状态管理
Vuex官方文档
Vue Router官方文档

@coconilu coconilu mentioned this issue Jun 23, 2020
68 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant