加载渲染过程
父beforeCreate -> 父created-> 父beforeMount-> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted
2020/2/19小于 1 分钟
父beforeCreate -> 父created-> 父beforeMount-> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted
<div id="root">
<component :is="type"></component> <!--其效果如同下面两行被注释的代码-->
<!-- <child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two> -->
<button @click="handleClick">change</button>
</div>
<script type="text/javascript">
Vue.component('child-one', {
template: '<div>child-one</div>'
})
Vue.component('child-two', {
template: '<div>child-two</div>'
})
var vm = new Vue({
el: '#root',
data: {
type: 'child-one'
},
methods: {
handleClick() {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
<div id="root">
<child> <!-- 组件标签 -->
<h1>hello</h1>
</child>
</div>
<script type="text/javascript">
Vue.component('child', { // 子组件
template: '<div><slot></slot></div>'
})
var vm = new Vue({
el: '#root'
})
</script>
<div id="root">
<child @click="handleClick"></child> <!--这里click是自定义事件-->
</div>
<script type="text/javascript">
Vue.component('child', {
template: '<button>Child</button>',
})
var vm = new Vue({
el: '#root'
methods: {
handleClick() {
alert('click')
}
}
})
</script>
子组件对父组件传递来的参数进行校验
Vue.component('my-component', {
props: {
// 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
propA: Number,
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
propF: {
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
})
<div id="root">
<table>
<tbody>
<row></row>
<row></row>
<row></row>
</tbody>
</table>
</div>
<script type="text/javascript">
Vue.component('row', {
template: '<tr><td>this is a row</td></tr>'
})
var vm = new Vue({
el: '#root'
})
</script>
通过ref
引用调用子组件内的方法并传入参数
父组件:
<子组件标签 ref="refName"></子组件标签>
methods: {
fnX(x) {
this.$refs.refName.fnY(x) // 调用子组件方法并传入值
}
}