[英]Ho to properly pass a method in a child component in Vue.js?
我有一個名為goback.vue的子組件,它的唯一功能是在導航歷史記錄中返回一步。 我問這個問題的原因是因為我試圖在許多其他組件中經常重用這個組件,並且我希望以后能夠在一個地方編輯樣式和模板。
這是組件goback.vue的代碼:
<template>
<span @click="backOneStep">
<svg type="submit" class="arrowleft" >
<use href="../static/icons/iconsset.svg#arrowleft"></use>
</svg>
</span>
</template>
<script>
export default {
name: 'goback',
data () {
return {
}
},
methods: {
backOneStep(){
window.history.go(-1)
},
}
}
<script>
然后在我的幾個父組件上,我以以下方式導入子組件:
<template>
<div class="building">
<div id="title">
<goback></goback> // using the child component here
</div>
</div>
</template>
<script>
import goback from './goback.vue';
export default {
components: {
goback
},
name: 'maincomponent',
data () {
return {
}
}
},
methods: {
backOneStep(){ // do I need to repeat this here?
window.history.go(-1)
},
}
}
</script>
首先,我想知道是否需要在所有父組件上重復該方法,或者我是否可以將它寫在我的子組件上。 其次,我收到一條錯誤消息:
[Vue 警告]:屬性或方法“backOneStep”未在實例上定義,但在渲染期間被引用。 通過初始化該屬性,確保該屬性是反應性的,無論是在數據選項中,還是對於基於類的組件。 請參閱: https ://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。
在發現
<Goback> at src/components/goback.vue
<Depts> at src/components/depts.vue
<App> at src/App.vue
<Root>
注意:我已經仔細閱讀了鏈接,但我仍然卡住了
在上一條錯誤消息之后,我也立即收到此錯誤消息:
[Vue 警告]:事件“點擊”的無效處理程序:未定義
在發現
<Goback> at src/components/goback.vue
<Depts> at src/components/depts.vue
<App> at src/App.vue
<Root>
能告訴我我能做些什么來避免這種情況嗎? 這和道具有關嗎? 我嘗試在 goback.vue 的數據中聲明“ backOneStep ”道具,但我不確定我是否做得正確。 我在這里想念什么?
您可以使用$emit
事件告訴父級在單擊子組件時“返回”:
<template>
<span @click="backOneStep">
<svg type="submit" class="arrowleft" >
<use href="../static/icons/iconsset.svg#arrowleft"></use>
</svg>
</span>
</template>
<script>
export default {
name: 'goback',
methods: {
backOneStep() {
this.$emit('back')
}
}
}
</script>
在父母中:
<template>
<div class="building">
<div id="title">
<goback @back="window.history.go(-1)"></goback>
</div>
</div>
</template>
這對我來說是這樣做的,因為我想在組件上隔離這個元素/功能的主要原因是能夠在一個地方更改元素的樣式:
子組件:
<template>
<span v-on:click="$emit('back')">
<svg type="submit" class="arrowleft" >
<use href="../static/icons/iconsset.svg#arrowleft"></use>
</svg>
</span>
</template>
<script>
export default {
name: 'goback',
data () {
return {
}
}
}
<script>
<style scoped>
// enter styles here
</style>
在父級上:
<template>
<div class="building">
<div id="title">
<goback @back="window.history.go(-1)"></goback>
</div>
</div>
</template>
<script>
import goback from './goback.vue';
export default {
components: {
goback
},
methods: {
backOneStep(){
window.history.go(-1)
},
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.