關於$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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM