Vue 组件间传值
程序员文章站
2022-07-03 16:33:34
...
Vue 组件传值
vue组件间传值分类
- 父子组件间传值:props
- 子父组件传值:emit
- 兄弟组件传值:eventbus
- 祖先子孙自建传值:高级用法provide、inject
整体案例
组件结构:Helloworld —> news —> mhead
祖组件
<template>
<div class="hello" style="border: 1px solid blue">
<h1>西出阳关无故人</h1>
<span>{{ msg }}</span>
<news :data='num' @ok=add></news>
</div>
</template>
<script>
import news from './news'
export default {
name: "HelloWorld",
components: {
news
},
created() {},
provide() {
return {
num: this.num
}
},
data() {
return {
msg: "你好,我叫王佳伟",
num: 10,
};
},
methods: {
add(num) {
console.log('子组件传回的值:', num);
},
}
};
</script>
<style scoped lang="scss">
</style>
父组件
<template>
<div class="hello" style="border: 1px solid red">
<h1>子组件</h1>
<p>{{ msg }}</p>
<mhead></mhead>
</div>
</template>
<script>
import mhead from './mhead';
export default {
name: "News",
components: {
mhead
},
props: ['num'],
created() {
console.log('父组件传进来的值:', this.num);
// $attrs收集器:收集属性
// $listeners收集器:收集事件
// 收集器收集会排除(props,class,style…)
console.log(this.$attrs, this.$listeners);
},
data() {
return {
msg: "这是子组件news"
};
},
methods: {}
};
</script>
<style scoped lang="scss">
</style>
孙组件
<template>
<div class="hello" style="border: 1px solid yellow">
<h1>这是子孙组件</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
name: "mhead",
created() {
console.log('这是爷爷组件传进来的:', this.num);
},
inject: ['num'],
data() {
return {
msg: "这是子孙组件"
};
},
methods: {}
};
</script>
<style scoped lang="scss">
</style>