当前位置:网站首页>92-兄弟组件间的传值问题
92-兄弟组件间的传值问题
2022-07-19 05:05:00 【longfei815】
92-兄弟组件间的传值问题
兄弟组件间的传值方式:
1 先子传父再父传子(不推荐)
2 中央事件总线(空的Vue对象)
3 Vuex状态管理(不是今天的内容)
中央事件总线(空的Vue对象)步骤有3步:
第1步: 创建一个空的Vue对象用来监听和触发自定义事件
第2步: 在需要被修改的组件中开启自定义事件监听
第3步: 触发第2步中的自定义事件
效果如下:点击“按钮2”,改变“按钮1”的颜色。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>92-兄弟组件间的传值问题</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id='app'>
<child1></child1>
<child2></child2>
</div>
<template id="tmpl1">
<button :style="{backgroundColor:bgc}">按钮1</button>
</template>
<template id="tmpl2">
<button @click="hdClick2">按钮2</button>
</template>
<script>
/*
兄弟组件间的传值方式:
1 先子传父再父传子(不推荐)
2 中央事件总线(空的Vue对象)
3 Vuex状态管理(不是今天的内容)
中央事件总线(空的Vue对象)步骤有3步:
第1步: 创建一个空的Vue对象用来监听和触发自定义事件
第2步: 在需要被修改的组件中开启自定义事件监听
第3步: 触发第2步中的自定义事件
*/
// 第1步: 创建一个空的Vue对象用来监听和触发自定义事件
let bus = new Vue();
let child1 = {
template:"#tmpl1",
data(){
return{
bgc:"red"
}
},
created(){
// 是一个生命周期函数之一(后面学)
// 什么时候执行这里的代码?? 组件被刚创建的时候, 现在记成 页面一刷新就执行
// 第2步: 在需要被修改的组件中开启自定义事件监听
// bus.$on("自定义事件名", 事件函数)
bus.$on("changeBgc",val=>{
this.bgc = val
});
}
}
let child2 = {
template: "#tmpl2",
methods:{
hdClick2(){
// 修改按钮组件1的bgc数据
// 第3步: 触发第2步中的自定义事件
bus.$emit("changeBgc", "#ccc");
}
}
}
new Vue({
el:'#app',
data:{
},
components:{
child1, child2
}
})
</script>
</body>
</html>
边栏推荐
猜你喜欢
整型及浮点型数据在内存中的存储
Openwrt manually installs the netdata plug-in
动态内存管理
Pytorch target detection coco API explanation data generation
Skillfully solve Young's matrix
Pytorch target detection data processing (II) extracting difficult samples, low AP samples
shell脚本编程
Pytorch target detection competition (I) data analysis
三子棋游戏
Dynamic memory request
随机推荐
Pytorch implements the use of data enhancement classification evaluations
Explain the full permutation problem in detail (different output results of different solutions)
贪心——删数
Share what you learned this week - detailed explanation of transformer model
C language structure knowledge sharing
原生JS完美实现深拷贝
学生成绩管理系统(c语言)
计算起始日期之间的中间日期
Student achievement management system (C language)
Using function pointer array to write calculator
C语言中动态内存的开辟
我的第一篇博客
[Day.2]约瑟夫环问题,如何用数组代替循环链表(详解)
Skillfully solve Young's matrix
长篇详解C语言操作符
4000字,让你明白递推及其例题做法(C语言,有图)
Learning diary 4- program structure and control statements
The project is lost after Jenkins restarts (including the download address of Jenkins plugins)
Greedy - deletion
第五十八篇:VS调试出现“覆盖。。。。是/N:否/A:全部)??”