vue.extend
Vue.extend 属于 Vue 的全局 API,在实际业务开发中我们很少使用,因为相比常用 Vue.component 写法使用 extend 步骤要更加繁琐一些。但是在一些独立组件开发场景中需要使用Vue.extend + $mount
Vue官网实例
参数: {Object} options
用法: 使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。 data 选项是特例,需要注意 - 在 Vue.extend() 中它必须是函数
<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')
结果如下:
<p>Walter White aka Heisenberg</p>
组件选项 extends(可理解为单继承,只接受一个extends)
允许声明扩展另一个组件(可以是一个简单的选项对象或构造函数),而无需使用 Vue.extend。这主要是为了便于扩展单文件组件。
<div id='app'></div>
<script>
let father = {
created(){
console.log('father的created()钩子')
},
data(){
return {
msg:'msg from father'
}
}
}
let child = new Vue({
el:'#app',
extends:father,
data:{
msg:'msg from child'
},
created(){
console.log('child的created钩子');
console.log(this.msg);
}
})
</script>
</body>
//上面例子表明了extends可以继承生命周期钩子函数.
<body>
<div id='app'></div>
<script>
let father = {
created(){
console.log('father的created()钩子')
},
data(){
return {
msg:'msg from father'
}
},
methods:{
say(){
console.log('hello world');
}
}
}
let child = new Vue({
el:'#app',
extends:father,
created(){
console.log('child的created钩子');
console.log(this.msg);
this.say();
}
})
</script>
</body>
进一步得出结论:extends甚至还能继承data和methods(当然重写会覆盖)
extends使得组件能像面向对象变成一样便于拓展。