面试题答案
一键面试- 使用事件冒泡机制:
- 在子组件中,按钮的点击事件处理函数正常编写。在处理完子组件逻辑后,事件会冒泡到父组件。
- 父组件在模板中监听来自子组件冒泡的点击事件。例如:
<!-- 子组件模板 --> <template> <button @click="handleChildClick">子组件按钮</button> </template> <script> export default { methods: { handleChildClick() { // 子组件点击处理逻辑 console.log('子组件点击事件处理'); } } }; </script>
<!-- 父组件模板 --> <template> <child - component @click="handleParentClick"></child - component> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleParentClick() { // 父组件点击处理逻辑 console.log('父组件点击事件处理'); } } }; </script>
- 使用
$nextTick
:- 在子组件中,点击事件处理函数里使用
$nextTick
来延迟父组件点击事件的触发。 - 例如:
<!-- 子组件模板 --> <template> <button @click="handleChildClick">子组件按钮</button> </template> <script> export default { methods: { handleChildClick() { // 子组件点击处理逻辑 console.log('子组件点击事件处理'); this.$nextTick(() => { this.$emit('parent - click'); }); } } }; </script>
<!-- 父组件模板 --> <template> <child - component @parent - click="handleParentClick"></child - component> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleParentClick() { // 父组件点击处理逻辑 console.log('父组件点击事件处理'); } } }; </script>
- 在子组件中,点击事件处理函数里使用