【问题标题】:vue.js prop does not get rendered in componentvue.js 道具没有在组件中呈现
【发布时间】:2020-05-01 16:29:46
【问题描述】:

我遇到了 Vue.js 道具渲染的问题。 我有两个组件:poi-point-adder 一个动态创建子表单,一个子表单 poi-component (被创建)。它们是这样的:

poi-point-adder:

var poiAdderComponent = Vue.component('poi-point-adder', {
  data: function(){
    return {
      children: []
    }
  },
  methods: {
    add() {
      this.children.push(poiComponent);
    }
  },
  mounted: function () {
    this.children = [];
  },
  template: `
  <div>
      <h1 class="title">Creator</h1>
      <div>
        <template v-for="(child, index) in children">
          <poi-component :id="index"></poi-component>
        </template>
      </div>
      <button class="button is-primary" @click="add()">+</button>
  </div>
  `
});

poi-component

var poiComponent = Vue.component('poi-component', {
    props: {
        index: String
      },
      data: {
      },
      methods: {
      },
    template: `
    <div :poi_index="index">
      <p>Hi n {{index}}</p>
    </div>`
    });

第二个问题出现。当我创建新实例时,index 道具不会被渲染(但poi_index 被赋予了正确的索引):

我做错了什么?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    poi-component 上,您不应该期待名为index 的道具,而是id

    另外:您不需要在组件周围使用&lt;template&gt;&lt;/template&gt;

    poi-component.vue

    var poiComponent = Vue.component('poi-component', {
      props: {
        id: String
      },
      data: {},
      methods: {},
      template: `
        <div :poi_index="id">
          <p>Hi n {{id}}</p>
        </div>`
    });
    

    poi-point-adder.vue

    var poiAdderComponent = Vue.component('poi-point-adder', {
      data: function(){
        return {
          children: []
        }
      },
      methods: {
        add() {
          this.children.push(poiComponent);
        }
      },
      mounted: function () {
        this.children = [];
      },
      template: `
      <div>
          <h1 class="title">Creator</h1>
          <div>
            <!-- you are passing down the prop "id" with the
            value of "index" -->
            <poi-component
              v-for="(child, index) in children"
              :key="index"
              :id="index"
            ></poi-component>
          </div>
          <button class="button is-primary" @click="add()">+</button>
      </div>
      `
    });
    

    更多信息:https://vuejs.org/v2/guide/components-props.html

    修改

    如果你使你的 prop 成为必需,如果传递的 prop 的名称不正确,你会看到错误/警告消息(下面的例子没问题,所以不应该显示错误):

    poi-component.vue

    var poiComponent = Vue.component('poi-component', {
      props: {
        id: {
          type: String,
          required: true
        }
      },
      data: {},
      methods: {},
      template: `
        <div :poi_index="id">
          <p>Hi n {{id}}</p>
        </div>`
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 2021-05-05
      • 2017-07-08
      • 2020-12-26
      • 2019-03-25
      • 2020-10-26
      • 2020-01-17
      • 2017-04-09
      相关资源
      最近更新 更多