gpt4 book ai didi

javascript - 如何在 Vue.js 的子组件中正确传递方法?

转载 作者:行者123 更新时间:2023-12-01 02:03:44 25 4
gpt4 key购买 nike

我有一个名为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 warn]: Property or method "backOneStep" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

 <Goback> at src/components/goback.vue
<Depts> at src/components/depts.vue
<App> at src/App.vue
<Root>

注意:我已经仔细阅读了链接,但我仍然卡住

紧接着上一个错误消息,我也收到此错误消息:

[Vue warn]: Invalid handler for event "click": got undefined

found in

 <Goback> at src/components/goback.vue
<Depts> at src/components/depts.vue
<App> at src/App.vue
<Root>

可以告诉我如何避免这种情况吗?这和 Prop 有关系吗?我尝试在 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>

关于javascript - 如何在 Vue.js 的子组件中正确传递方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50293426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com