祖先组件
<template>
<div>
<!-- 拿到子组件content的数据,通过自定义事件 -->
<!-- 2.在父组件中,通过v-on监听子组件中自定义的事件 -->
<p>祖先组件</p>
<Content @injectMsg="getChildMsg"></Content>
<h2>{{ message }}</h2>
<p>----祖先组件-----</p>
</div>
</template>
<script>
import Content from "./components/父子组件的通信-props-自定义事件.vue";
export default {
data() {
return {
message: "",
};
},
methods: {
getChildMsg: function (value) {
console.log(value);
this.message = value;
},
},
components: {
Content,
},
};
</script>
父组件Content
<template>
<div>
<p>父组件</p>
<!-- 组件是带有名称可复用的实例,单独功能模块的封装 -->
<Hello :message="msg" :list="list" ref="hello"></Hello>
<h2 ref="h2">我是content内容</h2>
<h2>{{ msg }}</h2>
<button @click="msg = '你好'" ref="button">改变msg</button>
<button @click="sendParent">提交数据给父组件</button>
<p>----父组件------</p>
</div>
</template>
<script>
import Hello from "./子组件和父组件之间相互访问(子)Hello.vue";
export default {
data() {
//让每一个组件对象都返回一份新的对象,不会造成数据污染
return {
msg: "helloword",
list: [1, 2, 3, 4],
};
},
mounted() {
console.log("父组件Content", this.$refs);//将打印当前组件中带ref属性的子组件
console.log("父组件Content", this.$refs.hello.a);
},
components: {
Hello,
},
methods: {
// 1.在子组件中,通过$emit来触发事件
sendParent: function () {
// this.$emit('自定义事件的名称','发送的事件参数');
this.$emit("injectMsg", this.msg);
},
},
};
</script>
子组件Hello
<template>
<div>
<p>子组件</p>
<h2>{{ message }}</h2>
<p>----子组件------</p>
</div>
</template>
<script>
export default {
data() {
return {
a: 10,
};
},
//字符串数组
// props: ["message"],
props: {
//1.类型的限制
// message: Number,
// 2.类型限制+默认值+必传值
message: {
type: String,
default: "你好",
required: true,
},
list: {
// 对象或者数组应当用工厂函数返回。
// 工厂函数会收到组件所接收的原始 props
// 作为参数
type: Array,
default() {
return [];
},
},
},
mounted() {
console.log("子组件Hello", this.$parent);
console.log("子组件Hello", this.$root);
},
};
</script>
初始状态
点击改变msg
后的显示状态
点击提交数据给父组件
后显示状态
总结
父组件获取子组件数据
1.在子组件中,通过
$emit
来触发事件
this.$emit(‘自定义事件的名称’,‘发送的事件参数’);
在父组件中,通过v-on
监听子组件中自定义的事件
2.父组件访问子组件:
$refs
ref:用来给元素或子组件注册引用信息,开发中常用
子组件获取父组件数据
1.在父组件中引用子组件,并传递参数
在子组件中定义props
<Hello :message="msg" :list="list"></Hello>
props: {
//1.类型的限制
// message: Number,
// 2.类型限制+默认值+必传值
message: {
type: String,
default: "你好",
required: true,
},
list: {
// 对象或者数组应当用工厂函数返回。
// 工厂函数会收到组件所接收的原始 props
// 作为参数
type: Array,
default() {
return [];
},
},
},
2.子组件访问父组件:
$parent
,在开发中尽量少用,组件的复用性很高
子组件访问根组件:$root