我有两个组件Sibling1
和Sibling2
并排放置.我想按下Sibling1
的一个按钮,触发Sibling2
的效果.
- 此逻辑只存在于父组件中,因此无需使其成为全局逻辑
- 要在组件外部提取这种效果并将其放在父级上并不容易
我想到的一种方法是这样做的:
// App.vue (parent)
const trigger = ref(null)
function setTrigger() {
trigger.value = Symbol('new trigger')
}
</script>
<template>
<SiblingOne @on-click="setTrigger" />
<SiblingTwo :trigger="trigger" />
</template>
// Sibling1.vue
<script setup>
const emit = defineEmits(['on-click'])
</script>
<template>
<button @click="emit('on-click')">update</button>
</template>
// Sibling2.vue
<script setup>
import { watch } from 'vue'
const props = defineProps({ trigger: null })
watch(
() => props.trigger,
() => console.log(new Date())
)
</script>
<template>Nothing to see here, check console</template>
我见过上面的几次模式,但也许还有更好的 Select .在vue 3中,什么是实现这一点的好方法?