1.定义父子模板template
<div class="container">
<my-father></my-father>
<my-father></my-father>
<my-father>
</my-father>
<!-- 此处无法调用子组件,子组件必须依赖于父组件进行展示 -->
<!-- <my-children></my-children> -->
</div>
<template id="father">
<div>
<h3>我是父组件</h3>
<h3>访问子组件的数据:</h3>
<h3>{{ msg }}</h3>
<h3>{{ name }}</h3>
<h3>{{ age }}</h3>
<h3>{{ user }}</h3>
<my-children></my-children>
<hr>
</div>
</template>
<template id="children">
<div>
<h6>我是子组件</h6>
<h6>访问子组件的数据:</h6>
</div>
</template>
2.创建Vue实例,如何建立父子关系
<script>
new Vue({
el: '.container',
components: {
'my-father': {//父组件
template: '#father',
data() {
return {
msg: "",
name: "",
age: null,
user: {
id: null,
username: ""
}
}
},
components: {
'my-children': { //子组件,只能在 my-father中调该组件
template: '#children',
data() {
return {
msg: "welcome children!",
name: "I'm a child!",
age: 6,
user: {
id: 1001,
username: 'admin'
}
}
}
}
}
}
}
})
</script>
技术:事件监听+事件触发
父组件在调用子组件时,监听子组件触发的自定义事件,并在父组件中定义回调方法,用来接收数据
<template id="father">
<div>
<h3>我是父组件</h3>
<h3>访问子组件的数据:</h3>
<h3>{{ msg }}</h3>
<h3>{{ name }}</h3>
<h3>{{ age }}</h3>
<h3>{{ user }}</h3>
<!-- 监听子组件触发的数据 -->
<my-children @e-child="getMsg"></my-children>
<hr>
</div>
</template>
在子组件中使用vm.$emit(事件名,数据)
触发自定义事件,将当前获取的数据,传给父类
components: {
'my-children': { //子组件,只能在 my-father中调该组件
template: '#children',
data() {
return {
msg: "welcome children!",
name: "I'm a child!",
age: 6,
user: {
id: 1001,
username: 'admin'
}
}
},
created() {
//触发事件,向父组件传递数据
this.$emit('e-child', this.msg,this.name,this.age,this.user)
}
}
}
父类定义一个方法,获取数据:
new Vue({
el: '.container',
components: {
'my-father': {//父组件
template: '#father',
data() {
return {
msg: "",
name: "",
age: null,
user: {
id: null,
username: ""
}
}
},
methods: {
getMsg(msg,name,age,user) {
this.msg = msg;
this.name = name;
this.age = age;
this.user = user;
}
}
}
}
})
打印结果:
相关文章: