在父组件 App.vue 中引用子组件 A.vue,把 A中的数据传给App.
ps:没看父组件传给子组件的先看看去。
1、代码
子组件 A.vue
<template>
<div>
<h3>这里是子组件的内容</h3>
<button v-on:click="spot">点一下就传</button>
</div>
</template>
<script>
export default {
methods: {
spot: function() {
// 与父组件通信一定要加上这句话
this.$emit("spot", '我是子组件传给父组件的内容就我。。')
}
}
}
</script>
父组件 App.vue
<template>
<div id="app">
<!-- 父组件直接用 v-on 来监听子组件触发的事件。 -->
<!-- 需跟子组件中的$emit组合使用 -->
<A v-on:spot="spot"/>
</div>
</template>
<script>
import A from './components/A'
export default {
name: 'App',
components: {
A
},
methods:{
spot:function(data){
console.log(data)
}
}
}
</script>
2、总结
1、$emit很重要,使用 $emit(事件名,参数) 触发事件
2、子组件需要某种方式来触发自定义事件
3、父组件直接用 v-on 来监听子组件触发的事件,需跟子组件中的$emit组合使用。