【问题标题】:Vue provide+inject on the same componentVue 在同一个组件上提供+注入
【发布时间】:2018-03-13 04:30:40
【问题描述】:

我想将provideinject 传递给可以使用slot 递归地包含自身的“page-section”组件。

目标是这些“页面部分”组件中的每一个都将其id 连接在其余传递下来的ID(由/ 分隔)之后,以创建所有包含组件的路径。

其中一些“页面部分”还可能包含其他类型的组件。

这是我尝试失败的方法:

 Vue.component('text-input', {
      props: ['text', 'id'],
      template: '<input type="text" :value="text"',
      inject: ['sectionPath']
    });

    Vue.component('page-section', {
      props: ['id'],
      template: '<div><slot></slot></div>',
      inject: {
        sectionPath: { default: '/' }
      },
      provide: {
        sectionPath: this.sectionPath + '/' + this.id
      }
    }
  });

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    你可以定义为prop,而不是一开始的inject。

    你需要使用函数来提供我相信的上下文。

    Vue.component('text-input', {
      props: ['text', 'id'],
      template: '<input type="text" :value="text" />',
      inject: ['sectionPath']
    });
    
    Vue.component('page-section', {
      template: '<div><slot></slot></div>',
      props: {
        id: {
          type: String,
          required: true
        }
        sectionPath: {
          type: String,
          required: true,
          default: '/'
        }
      }
      provide () {
        return {
          sectionPath: this.sectionPath + '/' + this.id
        }
      }
    });

    【讨论】:

    • 使用提供的函数形式解决了我的问题。谢谢
    猜你喜欢
    • 2020-11-16
    • 2020-03-07
    • 2019-04-04
    • 1970-01-01
    • 2021-06-22
    • 2021-02-23
    • 1970-01-01
    • 2019-08-26
    • 2019-05-04
    相关资源
    最近更新 更多