发现vue.js官网写的真的yyds呀,可以去官网学习一下
在组件的模板表达式中,可以直接使用 $emit
方法触发自定义事件 (例如:在 v-on
的处理函数中):
<!-- MyComponent -->
<button @click="$emit('someEvent')">Click Me</button>
父组件可以通过 v-on
(缩写为 @
) 来监听事件:
<MyComponent @some-event="callback" />
父组件App.vue:
<template>
<div>
父
<!-- 记得不加小括号 -->
<Child @ting="handleEvent" @CustomEvents="handleEvent2" />
<!-- 加上事件修饰符 .once 只执行一次 -->
<!-- <Child @ting.once="handleEvent" @CustomEvents="handleEvent2" /> -->
</div>
</template>
<script>
import Child from './Child.vue'
export default {
// 局部组件
components: {
Child
},
methods: {
handleEvent(asd) {
console.log('app-自定义事件', asd);
},
handleEvent2(qwe) {
console.log('app-自定义事件2', qwe);
}
}
}
</script>
<style scoped></style>
子组件Child.vue
<template>
<div>
子
<button @click="handleChild">子click</button>
<br>
<!-- 第二种写法:第一个参数是事件名,第二个参数是 子组件的状态-->
<button @click="$emit('CustomEvents', ChildTitle)">按钮二</button>
</div>
</template>
<script>
export default {
data() {
return {
ChildTitle: 'child123'
}
},
methods: {
handleChild() {
// console.log(this.ChildTitle);
// 事件名字 状态
this.$emit('ting', this.ChildTitle)
}
}
}
</script>
<style scoped>
div {
background-color: yellow;
}
</style>
运行截图:
再次改写一下前面一节的属性透传的案例
父组件App.vue
<template>
<div class="root">
<Navbar @event="handleEvent"></Navbar>
<Layout class="layout" :myshow="isShow"></Layout>
</div>
</template>
<script>
import Navbar from './components/Navbar.vue'
import Layout from './components/Layout.vue'
export default {
data() {
return {
isShow: false,
}
},
methods: {
handleEvent() {
this.isShow = !this.isShow
}
},
components: {
Navbar,
Layout
}
}
</script>
<style>
* {
margin: 0;
padding: 0;
}
.root {
display: flex;
flex-direction: column;
height: 100vh;
}
.navbar {
height: 50px;
}
.layout {
flex: 1;
display: flex;
}
</style>
子组件Layout.vue 跟之前的不变
<template>
<div>
<Sidebar v-if="myshow"></Sidebar>
<Content></Content>
</div>
</template>
<script>
import Content from './Content.vue'
import Sidebar from './Sidebar.vue'
export default {
props: ['myshow'],
components: {
Content,
Sidebar,
}
}
</script>
<style></style>
子组件Navbar.vue
<template>
<div class="navbar">
<button @click="handleClick">展开/折叠侧边栏</button>
<div>vue3单文件navbar</div>
</div>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
handleClick() {
console.log('navbar-click');
this.$emit('event',)
}
}
}
</script>
<style scoped>
div {
background-color: #555;
}
</style>
运行截图:运行结果跟上面的一章一样
点击后: