我正在建立一个与NUXT网站。
我已经在Pages文件夹中设置了页面组件。我希望有一个BasePage组件,然后将这个基本组件扩展到新的页面,这些页面将继承基本组件中常见的方法。
我试着用混音器,但它不起作用
例如,我有:
孩子们:
父级:
mixin (或父)有一个方法initPage()。
我也希望在子程序中具有相同的方法initPage()。当我从子页面调用initPage()时,我需要从父和子页面运行此方法。订单是父级,然后是子级。
基本上,我试图在NUXT中执行通常在OOP语言中继承基类的操作,然后在子类方法中调用super.initPage()。
我正在尝试使用optionMergeStrategies.methods,但没有运气。请帮帮忙。
谢谢
更新:
我确信可以使用自定义合并策略(使用optionMergeStrategies选项)来完成这项工作。我试过了,但不知道是怎么回事。所以我需要另一个解决方案。好的,我所做的就是,在混合(或父)中,我使方法名为_initPage() (注意下划线),而在页面组件(子组件)中,我保留了名称initPage (没有下划线)。现在,我需要做的就是从子组件和initPage()方法中使用_initPage()调用父方法。这与调用super.initPage()完全一样。这可以应用于任意多个方法,只需在混合(或父)方法中添加下划线,然后从子方法中调用它们。我将混合文件命名为pageMixins。这种混合方法有许多继承的方法,如_initPage、_animateIn、_animateOut、_dispose、loadPage.等。
父(混合文件):
_initPage: function() {
// code...
}子(页组件)
initPage: function() {
this._initPage();
// code...
}发布于 2018-12-24 06:43:25
为此,最好使用Vuejs父子沟通。子事件(this.$emit('yourEventName')) --一个事件发送给父和父--侦听(<child-component @yourEventName='initPage'>)事件,而不是调用它的相应函数(在父组件中)。然后,子组件继续在它的函数(initPageInChild () { this.$emit('yourEventName'); // after parent done run other statemnts here } )中运行语句。你也可以看到这个答案,https://stackoverflow.com/a/40957171/9605654 (非常好的解释)
const mainVue = new Vue({}),
parentComponent = new Vue({
el: '#parent',
mounted() {
this.$nextTick(() => {
console.log('in parent')
// in nuxt instead of mainVue use this
mainVue.$on('eventName', () => {
this.parentMsg = `I heard event from Child component ${++this.counter} times..`;
});
})
},
data: {
parentMsg: 'I am listening for an event..',
counter: 0
}
}),
childComponent = new Vue({
el: '#child',
methods: {
initPageInChild: function () {
mainVue.$emit('eventName');
this.childMsg = `I am firing an event ${++this.counter} times..`;
}
},
data: {
childMsg: 'I am getting ready to fire an event.',
counter: 0
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="parent">
<h2>Parent</h2>
<p>{{parentMsg}}</p>
</div>
<div id="child">
<h2>Child</h2>
<p>{{childMsg}}</p>
<button @click="initPageInChild">Child Call</button>
</div>
发布于 2021-12-15 11:22:33
如果对此感兴趣,这里有一个扩展Nuxt.js页面组件的解决方案
在我的例子中,我有一个页面来添加一个项目,一个页面来编辑一个现有的项目,它们是相似的。然而,由于Nuxt的路由机制,我需要有2个文件为它。因此,add.vue文件如下所示
<script>
import EditItemPage from './_id/edit'
export default {
extends: EditItemPage
// you can add `data()`, `methods`, `computed` below this line
}
</script>https://stackoverflow.com/questions/53902302
复制相似问题