如何扩展Nuxt页面组件?

时间:2018-12-23 08:42:25

标签: vuejs2 nuxt

我正在用NUXT建立一个网站。

我已经在Pages文件夹中设置了页面组件。我想拥有一个BasePage组件,然后将该基本组件扩展为新页面,这些页面将继承该基本组件中的常用方法。

我正在尝试使用mixins,但是它不起作用

例如,我有:

孩子:

  • 第a
  • b页

父母:

  • page-mixins

mixin(或父对象)具有initPage()方法。

我想在子级中也有相同的方法initPage()。从子页面调用initPage()时,我需要此方法从父子运行。顺序是父母然后是孩子。

基本上,我正在尝试在NUXT中执行的操作,通常是在继承基类然后在子类方法中调用super.initPage()的OOP语言中进行的操作。

我正在尝试使用optionMergeStrategies.methods,但是没有运气。请帮忙。

谢谢

更新:

我确信可以使用自定义合并策略(使用optionMergeStrategies选项)来完成这项工作。我尝试过,但是不知道它是如何工作的。所以我需要另一个解决方案。好吧,我所做的就是,在mixin(或父级)中,我将方法命名为_initPage()(注意下划线),而在页面组件(子级)中,我保留了名称initPage(无下划线)。现在,我需要做的只是从子组件到initPage()方法中,我只需使用_initPage()调用父方法。这就像调用super.initPage()一样。可以根据需要将其应用于任意多个方法,只需在mixin(或父)方法中添加下划线,然后从子方法中调用它们即可。我将混合文件命名为pageMixins。这个mixin具有许多继承的方法,例如_initPage,_animateIn,_animateOut,_dispose,loadPage等。

父母(mixins文件):

_initPage: function() {

  // code...

}

子级(页面组件)

initPage: function() {
  this._initPage();

  // code...

}

1 个答案:

答案 0 :(得分:0)

为此,最好使用Vuejs Parent-child communication Child 向父对象发出(this.$emit('yourEventName'))事件,而 parent 侦听(<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>

相关问题