import Vue from 'vue'
// 定义一个新组件,组件是一个对象
const newComponent = {
// 除了实例以外,组件的data必须是函数,作用是每个组件形成自己的作用域,避免变量互相影响
data () {
return {
text: 11
}
},
// 模版
template: `<div>{{ text }} -- {{ school }}</div>`,
// 接受来自父组件的参数
props: {
school: {
type: String,
default: ''
}
}
}
new Vue({
el: '#app',
components: {
newComponent
},
template: '<newComponent :school="school"/>',
// 实例的data可以是一个对象
data: {
school: '东北学校'
}
})
页面展示:
注意:
(1)props 的类型校验,如果类型不正确,依然页面显示正常,只不过浏览器 console 会报错,比如 school 赋值为 true (Boolean) 字段,页面依然会照常显示,浏览器报错
(2)如果props 传过来的是一个对象,指定对象的默认值,也要用函数
props: {
school: {
type: Object,
// 注意对象的默认值
default () {
return {
name: String
}
}
}
}
(3)组件的继承:两种方式
方法一:
import Vue from 'vue'
// 定义一个新组件,组件是一个对象
const newComponent = {
data () {
return {
text: 11,
school: {
name: '东北大学'
}
}
},
template: `<div>{{ text }} -- {{ school.name }}</div>`,
mounted () {
console.log('newComponent mounted')
}
}
// extendComponent 这个组件 Vue.extend 继承 newComponent
const extendComponent = Vue.extend(newComponent)
// 创建 extendComponent 实例
new extendComponent({
el: '#app',
// 覆盖 newComponent 的 data
data: {
text: 12,
school: {
name: '东北学'
}
},
// 覆盖原来的props
propsData: {
xx: 'xx'
},
mounted () {
console.log('new extendComponent mounted')
}
})
方法一继承:
1. 使用 Vue.extend 指令,然后 new 新的 extend
2. 覆盖原来的props 要使用 propsData
3. 生命周期,先执行 基本的,再执行 继承的
方法二继承:注意是 extends 有s
import Vue from 'vue'
// 定义一个新组件,组件是一个对象
const newComponent = {
data () {
return {
text: 11,
school: {
name: '东北大学'
}
}
},
template: `<div>{{ text }} -- {{ school.name }}</div>`,
mounted () {
console.log('newComponent mounted')
},
created () {
console.log('newComponent created')
}
}
// 使用extends 继承
const extendComponent = {
extends: newComponent, // 继承
// 覆盖 data
data () {
return {
text: 12,
school: {
name: '东大学'
}
}
},
mounted () {
console.log('extendComponent mounted')
},
created () {
console.log('extendComponent created')
}
}
new Vue({
el: '#app',
components: {
extendComponent
},
template: '<extendComponent />'
})
生命周期,先执行 基本的,再执行 继承的