关于$emit的用法
1、父组件可以使用 props 把数据传给子组件。
2、$emit子组件调用父组件的方法并传递数据
示例
父组件 $emitFa.vue
<template>
<div>
<div>$emit子组件调用父组件的方法并传递数据</div>
<h1>父组件数据:{{msg}}</h1>
<emit-ch @updateInfo="updateInfo" :sendData="msg"></emit-ch>
</div>
</template>
<script>
import emitCh from './$emitCh'
export default {
name: 'emitFa',
components: { emitCh },
data () {
return {
msg: '北京'
}
},
methods: {
updateInfo (data) { // 点击子组件按钮时触发事件
console.log(data)
this.msg = data.city // 改变了父组件的值
}
}
}
</script>
子组件 $emitCh.vue
<template> <div class="train-city"> <h3>父组件传给子组件的数据:{{sendData}}</h3> <br/><button @click='select()'>点击子组件</button> </div> </template> <script> export default { name: 'emitCh', // 相当于一个全局 ID,可以不写,写了可以提供更好的调试信息 props: ['sendData'], // 用来接收父组件传给子组件的数据 data () { return { } }, computed: { }, methods: { select () { let data = { city: '杭州' } this.$emit('updateInfo', data)// select事件触发后,自动触发updateInfo事件 } } } </script>
路由
import Vue from 'vue' import Router from 'vue-router' import EmitFa from '@/components/$emitFa'// 父组件 import EmitCh from '@/components/$emitCh' // 子组件 Vue.use(Router) export default new Router({ // mode: 'history', // 更改模式,去掉地址栏的 # routes: [ { path: '/', name: 'EmitFa', component: EmitFa, children: [{ path: 'EmitCh', name: 'EmitCh', component: EmitCh }] } ] })
转载自 https://www.jianshu.com/p/d9ea3bef858b