我对 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>
Run Code Online (Sandbox Code Playgroud)
// 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>
Run Code Online (Sandbox Code Playgroud)
Vue 中分派的事件朝一个方向传播:子 \xe2\x87\x92 父。如果您有一个组件 P(父组件)和子组件 C1(子组件 1)和 C2(子组件 2),则无法触发 C1 中的事件并将其发送到 C2。它将去P。
\n\n如果您有非常嵌套的结构(许多级别)并且您确实需要这样做,那么最简单的方法是调度和侦听不属于显示列表的内容(即全局内容)的事件。非常典型的解决方案是拥有所谓的“事件总线”——一个单独的虚拟 Vue 实例,仅用于事件。这是有关Vue 中全局事件总线的完整教程。
\n\n它看起来像这样:
\n\n// in some global file\nconst EventBus = new Vue();\n\n// in GC1 (parent -> child 1 -> grand child 1)\nEventBus.$emit(\'someEvent\', \'some-data\')\n\n// in GC5 (parent -> child 3 -> grand child 5)\nEventBus.$on(\'someEvent\', function(data) {\n console.log(data) // \'some-data\n})\nRun Code Online (Sandbox Code Playgroud)\n\n这样您就可以轻松地在各处调度/捕获事件。
\n\n祝你好运!:)
\n| 归档时间: |
|
| 查看次数: |
12839 次 |
| 最近记录: |