Vue.use()

官方文档

通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成:

  1. // 调用 `MyPlugin.install(Vue)`
  2. Vue.use(MyPlugin)
  3. new Vue({
  4. // ...组件选项
  5. })

也可以传入一个可选的选项对象:

  1. Vue.use(MyPlugin, { someOption: true })

Vue.use 会自动阻止多次注册相同插件,届时即使多次调用也只会注册一次该插件。

Vue.js 官方提供的一些插件 (例如 vue-router) 在检测到 Vue 是可访问的全局变量时会自动调用 Vue.use()。然而在像 CommonJS 这样的模块环境中,你应该始终显式地调用 Vue.use()

  1. // 用 Browserify 或 webpack 提供的 CommonJS 模块环境时
  2. var Vue = require('vue')
  3. var VueRouter = require('vue-router')
  4. // 不要忘了调用此方法
  5. Vue.use(VueRouter)

源码

  1. import { toArray } from '../util/index'
  2. export function initUse (Vue: GlobalAPI) {
  3. Vue.use = function (plugin: Function | Object) {
  4. const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
  5. // 已注册 - 遍历是否存在
  6. if (installedPlugins.indexOf(plugin) > -1) {
  7. return this
  8. }
  9. // additional parameters
  10. const args = toArray(arguments, 1)
  11. // 头插
  12. args.unshift(this)
  13. // 判断install方法存在
  14. if (typeof plugin.install === 'function') {
  15. plugin.install.apply(plugin, args)
  16. } else if (typeof plugin === 'function') {
  17. plugin.apply(null, args)
  18. }
  19. // 注册 - 存入
  20. installedPlugins.push(plugin)
  21. return this
  22. }
  23. }
  1. export function toArray (list: any, start?: number): Array<any> {
  2. start = start || 0
  3. let i = list.length - start
  4. const ret: Array<any> = new Array(i)
  5. while (i--) {
  6. ret[i] = list[i + start]
  7. }
  8. return ret
  9. }

Vue-route

路由模式

  • hash: http://localhost:8080/#/login
    hash值指的是地址栏#号及后面的字符,其发生改变不会导致浏览器向服务器发送请求
    hash值改变触发onhashchange事件,方便控制浏览器的进退控制
    兼容IE8
  • history:http://localhost:8080/login
    利用HTML5 History Interface pushState()和replaceState()方法
    pushState(state, title, url)


浏览器不会向服务端请求数据,直接改变url地址,但会记录pushState的历史记录,可以使用浏览器的前进、后退

replaceState(state, title, url)


不同于pushState,replaceState仅仅是修改了对应的历史记录
刷新地址请求访问服务器
兼容IE10