在组件的模板表达式中,可以直接使用 $emit
方法触发自定义事件 (例如:在 v-on
的处理函数中):
//子组件代码
<template>
<div>
<button @click="$emit('increaseBy', 1)">
Increase by 1
</button>
</div>
</template>
注意:@click="$emit('increaseBy', 1)"中里面的increaseBy与以下父组件的@increase-by是配对的,@click="$emit('increaseBy', 1)"里面的1可以看成传参可以给函数方法所用
//父组件代码
<template>
<div class="root">
<!-- <Navbar class="navbar"></Navbar>
<Layout class="layout"></Layout> -->
<div class="aaa" :style="{fontSize: count + 'px'}">
<Layout @increase-by="(n) => count += n" />
fbslfnkgfn
</div>
</div>
</template>
<script>
// import Navbar from './components/Navbar.vue'
import Layout from './components/Layout.vue'
export default {
data() {
return {
count: 10
}
},
components:{
// Navbar,
Layout
}
}
</script>
<style>
*{
margin:0;
padding: 0;
}
.aaa {
width: 500px;
height: 500px;
background-color: aqua;
}
.root{
display: flex;
flex-direction: column;
height: 100vh;
}
.navbar{
height: 50px;
}
.layout{
flex:1;
display: flex;
}
</style>
注意:以上代码的:style="{fontSize: count + 'px'}"中fontSize的s是大写的