props/$emit ``适用父子组件通信
ref与parent/children``适用父子组件通信
attrs/listeners,provide/inject`` 适用于隔代组件通信
vuex,EventBus``(事件总线) 适用于父子、隔代、兄弟组件通信
slot``插槽方式
attrs实例
父组件(这时候我们传了两个参数title和type)
javascript
<template>
<div>
<div class="father">我是父组件,点击传值给孙子组件</div>
<child :title="title" :type="type" />
</div>
</template>
<script>
import child from "./components/child";
export default {
components: {
child
},
data() {
return {
title: "",
type: ""
};
},
methods: {}
};
</script>
子组件(注意:子组件使用了title,那么孙子组件就拿不到title值。)
javascript
<template>
<div>
<div class="child">
<div>我是子组件{{title}}</div>
</div>
<grandson v-bind="$attrs" />
</div>
</template>
<script>
import grandson from "./grandson";
export default {
components: {
grandson
},
props: {
title: {
type: String,
default: ""
}
},
watch: {
$attrs() {
console.log(this.$attrs, "attrs");
},
},
data() {}
};
</script>
孙子组件(该组件只能显示type)
javascript
<template>
<div>
<div class="grandson">我是孙子组件{{title}}{{type}}</div>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: ""
},
type: {
type: String,
default: ""
}
},
watch: {
title() {
console.log(this.title, "=====孙子组件");
},
type() {
console.log(this.type, "=====孙子组件");
}
},
data() {
return {};
}
};
</script>