老师,子组件绑定点击事件有什么作用
来源:2-12 生命周期函数的新写法
啊聪聪
2023-03-12 14:48:15
相关代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>生命周期函数的新写法</title> <script src="https://unpkg.com/vue@next"></script> <style> </style> </head> <body> <div id="root"></div> </body> <script> const app = Vue.createApp({ // beforeMount => onBeforeMount // mounted => onMounted // beforeUpdate => onBeforeUpdate // beforeUnmount => onBeforeUnmount // unmouted => onUnmounted setup() { const { ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated, onRenderTracked, onRenderTriggered,onBeforeUnmount,onUnmounted } = Vue; const name = ref('dell'); let show = ref(true); onBeforeMount(() => { console.log('onBeforeMount'); }); onMounted(() => { console.log('onMounted'); }); onBeforeUpdate(() => { console.log('onBeforeUpdate'); }); onUpdated(() => { console.log('onUpdated'); }); // 页面开始渲染时收集响应式依赖,只执行一次,局部更新不执行 onRenderTracked(() => { console.log('onRenderTracked'); }); // 每次触发页面重新渲染时自动执行 onRenderTriggered(() => { console.log('onRenderTriggered'); }); onBeforeUnmount(() => { console.log('onBeforeUnmount'); }); onUnmounted(() => { console.log('onUnmounted'); }); const handleClick = () => { name.value = 'lee'; } // 通过handleHide事件控制v-if的值,从而实现销毁test组件 const handleHide = () => { show.value = !show.value; } return {name,handleClick, show,handleHide } }, template: ` <div @click="handleClick"> {{name}} </div> <div @click="handleHide">parent</div> <test v-if="show" /> ` }); app.component('test', { data() { return {show: true} }, methods: { handleClick() { this.show = !this.show; } }, // 给子组件test上添加v-if="show"。当点击parent文字时控制添加或移出子组件, // 然后查看子组件对应的卸载函数执行结果 beforeUnmount() { console.log('test组件 onBeforeUnmount'); }, unmouted() { console.log('test组件 onUnmounted'); }, template: `<div @click="handleClick">child</div>` }); const vm = app.mount('#root'); </script> </html>
相关截图:
1回答
好帮手慕久久
2023-03-12
同学你好,解答如下:
1、子组件绑定事件后,可以通过事件向父组件传递数据。这一点,后面课程会详细讲,可以带着问题往后学习。
2、除了传递数据,还可以利用事件实现自己内部的逻辑。比如子组件里面有个列表,可以通过事件控制该列表是否显示:
祝学习愉快!
相似问题
回答 1
回答 1