讨论致同国际网站建设情况,制作网页的网站推荐,wordpress 图片样式,无锡市滨湖区建设局网站1. 借助父组件传参
A 组件派发一个事件#xff0c;修改 flag 的值#xff0c;先传递给父组件#xff0c;然后由父组件传递给 B 组件。
缺点#xff1a;必须由 App.vue 处理中间逻辑。
A.vue
templatediv classAh1A组件/h1…1. 借助父组件传参
A 组件派发一个事件修改 flag 的值先传递给父组件然后由父组件传递给 B 组件。
缺点必须由 App.vue 处理中间逻辑。
A.vue
templatediv classAh1A组件/h1button clickemitB派发一个事件/button/div
/templatescript setup langts
const emit defineEmits([on-click])
let flag false
const emitB () {flag !flagemit(on-click, flag)
}
/scriptstyle scoped
.A {width: 200px;height: 200px;color: #fff;background: blue;
}
/styleApp.vue
templatedivA on-clickgetFlag/AB :flagFlag/B/div
/templatescript setup langts
import A from ./components/A.vue;
import B from ./components/B.vue;
import { ref } from vue
let Flag refboolean(false)
const getFlag (flag:boolean) {Flag.value flag
}
/scriptstyle scoped/styleB.vue
templatediv classBh1B组件/h1{{ flag }}/div
/templatescript setup langts
type Props {flag: boolean
}
definePropsProps()/scriptstyle langscss scoped
.B{width: 200px;height: 200px;color: #fff;background: red;
}
/style2. Event Bus
Event Bus事件总线是一种在Vue中实现组件间通信的模式。它使用了Vue实例作为中央的事件中心允许任何组件注册监听器并触发事件。通过事件总线兄弟组件之间可以进行解耦合的通信。
原理是利用了 JavaScript 设计模式的发布-订阅Publish-Subscribe Pattern然后由事件调度中心Event Loop进行处理。
// Bus.tstype BusClass {emit: (name: string) voidon: (name: string, callback: Function) void
}type PramsKey string | number | symboltype List {[key: PramsKey]: ArrayFunction
}class Bus implements BusClass {list: Listconstructor() {this.list {}}emit(name: string, ...args:Arrayany): void {let eventName: ArrayFunction this.list[name]eventName.forEach(fn {fn.apply(this, args)})}on(name: string, callback: Function): void {let fn:ArrayFunction this.list[name] || []fn.push(callback)this.list[name] fn}
}
export default new Bus()!-- A.vue --
templatedivh1A组件/h1button clickemitB派发一个事件/buttonhr/div
/templatescript setup langts
import Bus from ../Bus
let flag false
const emitB () {flag !flagBus.emit(on-click, flag)
}
/scriptstyle scoped/style!-- B.vue --
templatedivh1B组件/h1{{ Flag }}/div
/templatescript setup langts
import Bus from ../Bus
import { ref } from vue
let Flag ref(false)
Bus.on(on-click, (flag:boolean) {Flag.value flag
})/scriptstyle scoped/style!-- App.vue --
templatedivA/AB/B/div
/templatescript setup langts
import A from ./components/A.vue
import B from ./components/B.vue/scriptstyle scoped/style