3-3.vue的组件component:子组件向父组件传递数据
子组件向父组件传递数据是通过$emit来实现的,当子组件 触发某个事件后就可以通过$emit来发射一个自定义事件,父组件监听到该事件后获取数据
1.代码展示
<body>
<div id='app'>
<p>{{fatherTitle}}</p>
<cpn @childgive='fathershow'></cpn>
</div>
<template id='cpn'>
<div>
这是组件的数据
<button @click='btnchild'>用来发射数据</button>
</div>
</template>
<script>
// 一步到位
const cpn = {
template: "#cpn",
data() {
return {
title: '这是子组件向父组件传递的数据'
}
},
methods: {
btnchild() {
this.$emit('childgive', this.title);
}
}
}
const app = new Vue({
el: '#app',
data: {
fatherTitle: ''
},
// 局部注册
components: {
cpn
},
methods: {
fathershow(fathershow) {
this.fatherTitle = fathershow;
}
}
});
</script>
</body>