我有一個呼叫 API 的按鈕組件,我想將回傳的回應推送到父級,在那里它將成為 'translatedText' 道具,但是,由于錯誤,我相信我錯誤地使用了 $emit :`未捕獲(承諾)型別錯誤:無法讀取未定義的屬性(讀取“$emit”)。我如何最好地捕獲回應資料并將其傳遞給我的父道具,并且在這種情況下使用 $emit 是最佳用途?
翻譯按鈕.vue
<template>
<b-button type="is-primary" @click="loadTranslations()">übersetzen</b-button>
</template>
<script>
export default {
name: "TranslationButton",
props: {
translatedText: ''
},
methods: {
loadTranslations() {
fetch('http://localhost:3000/ccenter/cc_apis')
.then(function(response) {
return response.text();
})
.then(function(data) {
console.log(data);
this.$emit('translatedText', this.data);
console.log(data)
})
},
},
};
</script>
父組件道具:
props: {
data: Array,
translatedText: '',
showAttachments: {
type: Boolean,
default: false,
}
},
如何在父組件中呼叫子組件:
<translation-button @translatedText="loadTranslations()" />
uj5u.com熱心網友回復:
將資料從子級傳遞到父級時的最佳實踐是發出事件。
this.$root.$emit('translatedText', this.data);
比
this.$root.$on('translatedText', () => { // do stuff })
uj5u.com熱心網友回復:
通過發出您將值傳遞給父組件,@translatedText="loadTranslations()" - 它的事件監聽器,在您的子組件上觸發
做@translatedText="loadTranslations" 而不是@translatedText="loadTranslations()"
并將此 loadTranslations 作為方法添加到父組件
順便提一句
如果你不使用箭頭函式,而你使用 this.data 它指向傳遞給 .then 的物件,我猜它將是未定義的......
uj5u.com熱心網友回復:
問題在于this. 它不再指向 promise then() 方法中的組件。您應該創建一個新變數并使用 的值對其進行初始化,this然后使用該變數來發出事件。
例如
loadTranslations() {
const _this = this;
fetch().then(response => _this.$emit(response));
}
uj5u.com熱心網友回復:
如果你想將資料從孩子傳遞給父母,你需要像下面的代碼一樣使用 $emit
孩子:
<template>
<b-button type="is-primary" @click="loadTranslations">übersetzen</b-button>
</template>
<script>
export default {
name: "TranslationButton",
props: {
TranslatedText: ''
},
methods: {
loadTranslations() {
const self= this; // change added
fetch('http://localhost:3000/ccenter/cc_apis')
.then(function(response) {
return response.text();
})
.then(function(data) {
console.log(data);
self.$emit('changeTitle', data) // change added
})
}
}
</script>
家長:
<template>
<translation-button @changeTitle="ChangeT" />
</template>
......
methods:{
ChangeT(title)
{
console.log(title)
},
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359413.html
