目录一、组件间的通信方式分类二、props传递数据三、$emit 触发自定义事件四、ref标记五、EventBus事件总线六、$parent 或 $root七、Vuex八、总结一、组
适用场景:父组件传递数据给子组件;
Person.vue
<template>
<div>
Person
<Student1 name="jack" age="18"></Student1>
</div>
</template>
<script>
import Student1 from './Student1'
export default {
name: 'Person',
components: {
Student1,
},
</script>
Student1.vue
<template>
<div>
Student1
{{name}},{{age}}
</div>
</template>
<script>
export default {
name: 'Student1',
props: {
name: String,
age:Number,
}
}
</script>
效果
$emit
触发自定义事件,$emit
第二个参数为传递的数值;Student1.vue
<template>
<div>
Student1
<button @click="giveData()">点我传递数据</button>
</div>
</template>
<script>
export default {
name: 'Student1',
methods: {
giveData() {
this.$emit('add', '12345');
}
},
}
</script>
Person.vue
<template>
<div>
Person
<Student1 @add="cartAdd($event)"></Student1>
</div>
</template>
<script>
import Student1 from './Student1'
export default {
name: 'Person',
components: {
Student1,
},
methods: {
cartAdd(event) {
console.log(event);
}
},
}
</script>
<template>
<div>
Person
<Student2 ref="foo"></Student2>
<button @click="getRef()">点击获取ref数据</button>
</div>
</template>
<script>
import Student2 from "./Student2";
export default {
name: "Person",
components: {
Student2,
},
methods: {
getRef() {
console.log(this.$refs.foo);
},
},
};
</script>
效果
$emit
触发自定义事件,$emit
第二个参数为传递的数值$on
监听自定义事件beforeCreate() {
Vue.prototype.$bus = this
}
Student2.vue
<template>
<div>
Student2
<button @click="getBus()">点我获取全局事件总线数据</button>
</div>
</template>
<script>
export default {
name: 'Student2',
data() {
return {
name: 'fanafan',
age:'17'
}
},
methods:{
getBus(){
this.$bus.$emit('bus',this.name)
}
}
}
</script>
Student1.vue
mounted() {
this.$bus.$on('bus', (data) => {
console.log(data)
})
},
使用方法类似全局事件总结
Vue.prototype.$parent = this
// 传数据
this.$parent.$emit('parent',this.age)
//接数据
this.$parent.$on('parent', (data) => {
console.log(data);
})
到此这篇关于Vue组件通信深入分析的文章就介绍到这了,更多相关Vue组件通信内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Vue组件通信深入分析
本文链接: https://lsjlt.com/news/171884.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0