深入浅析Vue中mixin和extend的区别和使用场景


Posted in Javascript onAugust 01, 2019

Vue中有两个较为高级的静态方法mixin和extend,接下来我们来讨论下关于他们各自的原理和使用场景。

Mixin:

原理:

先来看看官网的介绍:

参数:{Object} mixin

用法:

混入也可以进行全局注册。使用时格外小心!一旦使用全局混入,它将影响每一个之后创建的 Vue 实例。使用恰当时,这可以用来为自定义选项注入处理逻辑。

// 为自定义的选项 'myOption' 注入一个处理器。
   Vue.mixin({
    created: function () {
     var myOption = this.$options.myOption
     if (myOption) {
      console.log(myOption)
     }
    }
   })
   
   new Vue({
    myOption: 'hello!'
   })
   // => "hello!"

我们知道,Vue.mixin传递的这个参数对象,在初始化Vue实例的时候会merge到options上,下面是Vue源码中对mixin的操作。

// src\core\global-api\mixin.js
 export function initMixin (Vue: GlobalAPI) {
  Vue.mixin = function (mixin: Object) {
   this.options = mergeOptions(this.options, mixin)
   return this
  }
 }
// src\core\instance\index.js
 function Vue (options) {
   if (process.env.NODE_ENV !== 'production' &&
   !(this instanceof Vue)
   ) {
   warn('Vue is a constructor and should be called with the `new` keyword')
   }
   this._init(options)
 }
 
 initMixin(Vue)
 ...
 
 export default Vue

也就是说,mixin只是对我们在初始化Vue实例时传递的配置对象的一个扩展。

就像上面官网实例写的例子,我们在执行Vue.mixin方法时传递一个配置对象进去,对象里面有个created勾子函数,通过源码我们可以看到这个传递进来的对象最终会和我们在初始化实例也就是new Vue(options)时的这个options合并(通过上面源码中的mergeOptions方法),保存在option上。

使用场景:

当我们需要全局去注入一些methods,filter或者hooks时我们就可以使用mixin来做。 比如我们希望每一个Vue实例都有一个print方法,我们就可以这么做:

Vue.mixin({
    methods: {
      print() {
        console.log(`我是一个通过mixin注入的方法!`)
      }
    }
  })

或者我们想要去监听在什么阶段时什么组件被加载了,被卸载了等等,我们可以这么做:

Vue.mixin({
    mounted() {
      console.log(`${this.$route.name} component mounted!`)
    },
    destroyed() {
      console.log(`${this.$route.name} component destroyed!`)
    }
  })

如果我们并不想给每一个组件实例都混入这些配置options,而只是个别的组件,最好不要使用mixin,它可能会影响到我们组件的性能。

Extend:

原理:

先来看看官网的介绍:

参数:{Object} options

用法:

使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。

data 选项是特例,需要注意 - 在 Vue.extend() 中它必须是函数。

data必须是函数是为了防止各个实例的数据混乱,闭包的应用。

<div id="mount-point"></div>
// 创建构造器
var Profile = Vue.extend({
 template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
 data: function () {
  return {
   firstName: 'Walter',
   lastName: 'White',
   alias: 'Heisenberg'
  }
 }
})
// 创建 Profile 实例,并挂载到一个元素上。
new Profile().$mount('#mount-point')

再来看看源码里面关于Vue.extend的实现:

Vue.extend = function (extendOptions: Object): Function {
  extendOptions = extendOptions || {}
  const Super = this
  const SuperId = Super.cid
  const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})
  if (cachedCtors[SuperId]) {
   return cachedCtors[SuperId]
  }

  const name = extendOptions.name || Super.options.name
  if (process.env.NODE_ENV !== 'production' && name) {
   validateComponentName(name)
  }

  const Sub = function VueComponent (options) {
   this._init(options)
  }
  Sub.prototype = Object.create(Super.prototype)
  Sub.prototype.constructor = Sub
  Sub.cid = cid++
  Sub.options = mergeOptions(
   Super.options,
   extendOptions
  )
  Sub['super'] = Super

  // For props and computed properties, we define the proxy getters on
  // the Vue instances at extension time, on the extended prototype. This
  // avoids Object.defineProperty calls for each instance created.
  if (Sub.options.props) {
   initProps(Sub)
  }
  if (Sub.options.computed) {
   initComputed(Sub)
  }

  // allow further extension/mixin/plugin usage
  Sub.extend = Super.extend
  Sub.mixin = Super.mixin
  Sub.use = Super.use

  // create asset registers, so extended classes
  // can have their private assets too.
  ASSET_TYPES.forEach(function (type) {
   Sub[type] = Super[type]
  })
  // enable recursive self-lookup
  if (name) {
   Sub.options.components[name] = Sub
  }

  // keep a reference to the super options at extension time.
  // later at instantiation we can check if Super's options have
  // been updated.
  Sub.superOptions = Super.options
  Sub.extendOptions = extendOptions
  Sub.sealedOptions = extend({}, Sub.options)

  // cache constructor
  cachedCtors[SuperId] = Sub
  return Sub
 }
}

首先我们可以看到,extend方法返回的Sub其实是一个构造函数,而且继承自Vue,也就是说extend方法返回的是Vue的一个子类。

Sub.prototype = Object.create(Super.prototype)
  Sub.prototype.constructor = Sub

这两行代码其实就是实现Sub对Vue的继承,源码中有一行是

const Super = this

所以这里的Super指的就是Vue。

Sub.options = mergeOptions(
   Super.options,
   extendOptions
)

我们注意到在extend中也会对传进来的配置option和Vue原来的options做一个合并。

使用场景:

当我们不需要全局去混入一些配置,比如,我们想要获得一个component。我们可以使用Vue.component(),也可以使用Vue.extend()。

const ChildVue = Vue.extend({
  ...options
})

new ChildVue({
  ...options
})

注意extend得到的是一个Vue的子类,也就是构造函数。

区别:

mixin是对Vue类的options进行混入。所有Vue的实例对象都会具备混入进来的配置行为。

extend是产生一个继承自Vue类的子类,只会影响这个子类的实例对象,不会对Vue类本身以及Vue类的实例对象产生影响。

总结

以上所述是小编给大家介绍的Vue中mixin和extend的区别和使用场景,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Javascript 相关文章推荐
js仿百度有啊通栏展示效果实现代码
May 28 Javascript
document.getElementById获取控件对象为空的解决方法
Nov 20 Javascript
JS求平均值的小例子
Nov 29 Javascript
javascript中的取反再取反~~没有意义
Apr 06 Javascript
table insertRow、deleteRow定义和用法总结
May 14 Javascript
JS函数的几种定义方式分析
Dec 17 Javascript
微信小程序 rpx 尺寸单位详细介绍
Oct 13 Javascript
jQuery的extend方法【三种】
Dec 14 Javascript
jQuery Easyui datagrid editor为combobox时指定数据源实例
Dec 19 Javascript
完美解决spring websocket自动断开连接再创建引发的问题
Mar 02 Javascript
原生js实现仿window10系统日历效果的实例
Oct 31 Javascript
jquery+ajax实现异步上传文件显示进度条
Aug 17 jQuery
在Vue环境下利用worker运行interval计时器的步骤
Aug 01 #Javascript
详解Vue2.5+迁移至Typescript指南
Aug 01 #Javascript
微信小程序组件传值图示过程详解
Jul 31 #Javascript
vue.js实现回到顶部动画效果
Jul 31 #Javascript
vue实现滑动超出指定距离回顶部功能
Jul 31 #Javascript
Vue实现回到顶部和底部动画效果
Jul 31 #Javascript
详解mpvue实现对苹果X安全区域的适配
Jul 31 #Javascript
You might like
PHP中ADODB类详解
2008/03/25 PHP
PHP 多进程 解决难题
2009/06/22 PHP
队列在编程中的实际应用(php)
2010/09/04 PHP
PHP图像处理之使用imagecolorallocate()函数设置颜色例子
2014/11/19 PHP
JavaScript的变量作用域深入理解
2009/10/25 Javascript
Js注册协议倒计时的小例子
2013/06/24 Javascript
js点击出现悬浮窗效果不使用JQuery插件
2014/01/20 Javascript
Javascript中的五种数据类型详解
2014/12/26 Javascript
Jquery常用的方法汇总
2015/09/01 Javascript
vue-resource 拦截器使用详解
2017/02/21 Javascript
使用bootstrap插件实现模态框效果
2017/05/10 Javascript
JS实现简易的图片拖拽排序实例代码
2017/06/09 Javascript
ES6中的rest参数与扩展运算符详解
2017/07/18 Javascript
在 Typescript 中使用可被复用的 Vue Mixin功能
2018/04/17 Javascript
vue计算属性computed的使用方法示例
2019/03/13 Javascript
jQuery HTML获取内容和属性操作实例分析
2020/05/20 jQuery
django自定义Field实现一个字段存储以逗号分隔的字符串
2014/04/27 Python
python实现将html表格转换成CSV文件的方法
2015/06/28 Python
详解使用Python处理文件目录的相关方法
2015/10/16 Python
pandas的object对象转时间对象的方法
2018/04/11 Python
Python 之 Json序列化嵌套类方式
2020/02/27 Python
python 实现有道翻译功能
2021/02/26 Python
中国一家综合的外贸B2C电子商务网站:DealeXtreme(DX)
2020/03/10 全球购物
在网络中有两台主机A和B,并通过路由器和其他交换设备连接起来,已经确认物理连接正确无误,怎么来测试这两台机器是否连通?如果不通,怎么来判断故障点?怎么排
2014/01/13 面试题
奥巴马演讲稿
2014/01/08 职场文书
司机辞职报告范文
2014/01/20 职场文书
优秀交警事迹材料
2014/01/26 职场文书
学校党员对照检查材料
2014/08/28 职场文书
迎国庆演讲稿
2014/09/05 职场文书
县政府领导班子“四风”方面突出问题整改措施
2014/09/23 职场文书
党委工作总结2015
2015/04/27 职场文书
消防安全月活动总结
2015/05/08 职场文书
基于Go Int转string几种方式性能测试
2021/04/28 Golang
使用RedisTemplat实现简单的分布式锁
2021/11/20 Redis
解决vue-router的beforeRouteUpdate不能触发
2022/04/14 Vue.js
MySQL中TIMESTAMP类型返回日期时间数据中带有T的解决
2022/12/24 MySQL