gpt4 book ai didi

vue.js - 将事件从一个组件传递到其他组件

转载 作者:行者123 更新时间:2023-12-03 06:44:24 26 4
gpt4 key购买 nike

我真的是 Vue 的新手,似乎无法理解事件是如何从一个组件传递到其他组件的。我目前正在使用 v-blur我想模糊除单击的组件之外的每个组件。我想通过在单击原始组件时将事件传递给其他组件,我可以获得想要的效果。非常感谢任何帮助!

// Parent.vue
<template>
<div id="Parent">
<child-one @toggle-blur="toggleChildBlur"/>
<child-two @toggle-blur="toggleChildBlur"/>
<child-three @toggle-blur="toggleChildBlur"/>
</div>
</template>

<script>
import ChildOne from './ChildOne'
import ChildTwo from './ChildTwo'
import ChildThree from './ChildThree'

export default {
name: 'Parent',
components: {
ChildOne, ChildTwo, ChildThree
},
methods: {
toggleChildBlur () {
// Blur every child except the clicked one?
}
},
data () {
return {}
}
}
</script>

// ChildOne.vue, basically the same for two and three aswell
<template>
<div id="child-one" v-blur="blurConfig" @click="$emit('toggle-blur')"></div>
</template>

<script>
export default {
name: 'ChildOne',
methods: {
toggleBlur () {
this.blurConfig.isBlurred = !this.blurConfig.isBlurred;
}
},
data () {
return {
blurConfig: {
isBlurred: false,
opacity: 0.3,
filter: 'blur(1.2px)',
transition: 'all .3s linear'
}
}
}
}
</script>

最佳答案

在 Vue 中调度的事件沿一个方向传播:子 ⇒ 父。如果您有组件 P(父级)和子级 C1(子级 1)和 C2(子级 2),则无法在 C1 中触发事件并将其发送到 C2。它将转到 P。

如果你有非常嵌套的结构(很多层次)并且你真的需要这样做,最简单的方法是在不属于显示列表的东西上调度和监听事件,即全局的东西。非常典型的解决方案是拥有所谓的“事件总线”——一个单独的虚拟 Vue 实例,您仅将其用于事件。这是关于 Global Event Bus in Vue 的完整教程.

看起来像这样:

// in some global file
const EventBus = new Vue();

// in GC1 (parent -> child 1 -> grand child 1)
EventBus.$emit('someEvent', 'some-data')

// in GC5 (parent -> child 3 -> grand child 5)
EventBus.$on('someEvent', function(data) {
console.log(data) // 'some-data
})

通过这种方式,您可以轻松地在各处调度/捕获事件。

祝你好运! :)

关于vue.js - 将事件从一个组件传递到其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52671815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com