![](/img/trans.png)
[英]Vue.js globalEventBus catch events from window object?
[英]Cannot catch custom events on Vue.JS
我正在嘗試使用事件將數據從子組件傳遞到父組件,但我無法捕獲它。 該事件在子組件 function 上觸發,但在父組件 function 上未捕獲。
有人能弄清楚為什么沒有調用 callbackMethod 嗎?
我已經嘗試過使用 kebab-case 的其他名稱,嘗試不使用自定義數據/參數,嘗試在模板標簽上捕獲事件,嘗試將子組件包裝到 div 中,嘗試刪除 v-on 語句上的括號。 ..
子組件:
HTML
<v-btn
color="primary"
icon
small
elevation="1"
@click="openSettings"
>
<v-icon>
mdi-dots-vertical
</v-icon>
</v-btn>
JavaScript
export default {
name: "ChildComponent",
components: {
OtherChild
},
props: {
my_prop: Object
},
methods: {
openSettings: function () {
// always use kebab-case for event names!
// (https://v2.vuejs.org/v2/guide/components-custom-events.html)
this.$emit("open-child-settings", this.my_prop)
console.log("event")
}
}
父組件:
HTML
<v-container>
<ChildComponent @open-child-settings="callbackMethod($event)"/>
</v-container>
JavaScript
export default {
name: 'ParentComponent',
components: {
ChildComponent,
OtherChildComponent
},
methods: {
callbackMethod: function (my_prop){
this.settingsDialog = true;
this.tempProp = my_prop;
console.log("callback")
}
}
依賴項
"dependencies": {
"core-js": "^3.6.5",
"dotenv": "^8.2.0",
"vue": "^2.6.11",
"vuetify": "^2.2.11"
}
編輯:在沙盒上添加了代碼,這樣您就可以看到 Vue.js 擴展的整個全景圖和一些快照:
通過以下方式更新您的父組件:
<v-container>
<ChildComponent @open-child-settings="callbackMethod"/>
</v-container>
根據我的理解,這里不需要 $event 。 所以,只需刪除它並運行它。 它會起作用的。
看到這個 - 從子組件共享數據到父組件
假設my_prop
在子組件中定義,試試這個:
const childcomponent = Vue.component('child-component', { template: '#child-component', props: { my_prop: Object }, methods: { openSettings: function () { this.$emit("open-child-settings", this.my_prop); //pass my_prop } } }); new Vue({ el: '#app', vuetify: new Vuetify(), components: { childcomponent }, data: () => ({ settingsDialog: false, tempProp: null, propData: {id:1} }), methods: { callbackMethod: function (my_prop){ this.settingsDialog = true; this.tempProp = my_prop; } } });
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <v-app id="app"> <v-container> <childcomponent @open-child-settings="callbackMethod($event)":my_prop="propData" /> </v-container> settingsDialog: {{settingsDialog}}<br> tempProp: {{tempProp}} </v-app> <template id="child-component"> <v-btn color="primary" icon small elevation="1" @click="openSettings" > <v-icon>mdi-dots-vertical</v-icon> </v-btn> </template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.