如何在Vue中使用自定义组件获取数组数据

问题描述 投票:0回答:3

我将一个数据数组传递给 Vue js 中的自定义组件,并希望将其放在我的模板中定义的 a 中,但出现 Missing required prop: "students" 错误。这是我的代码。

自定义组件:

customElements.define('students-list', defineCustomElement({
template: `<ul :classes="classes">
                <li v-for="st in students"
                    :key="st.name">
                    {{ st.name }}
                </li>
            </ul>
                </div>`,
props: {
    classes: {
        type: String,
        required: true,
    },
    students: {
        type: Array,
        required: true
    }

},
data() {
    return {
        
    }
}

}));

我用来调用它的代码是:

<students-list classes="col-sm-12" :students = "[{name: 'John'},{name: 'Sarah'},{name: 'Dave'}]"></students-list>
vue.js vue-component
3个回答
0
投票

根据您的代码,您似乎正在尝试从父组件访问子组件的数据数组,即

<students-list>
。如果是,就给你 :

Vue.component('studentslist', {
  // declare the props
  props: ['students'],
  // just like data, the prop can be used inside templates
  // and is also made available in the vm as this.message
  template: `<div>
                     <ul>
                <li v-for="st in students"
                    :key="st.name">
                    {{ st.name }}
                </li>
            </ul>
                    </div>`
});

var app = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <studentsList classes="col-sm-12" :students="[{name: 'John'},{name: 'Sarah'},{name: 'Dave'}]"></studentsList>
</div>


0
投票

您可以尝试在方法中定义一个函数,例如

students() {
  return [{name: 'John'},{name: 'Sarah'},{name: 'Dave'}];
},

并切换

:students = "[{name: 'John'},{name: 'Sarah'},{name: 'Dave'}]"

:students="students"

0
投票

Web 组件仅支持原始 String、Boolean 和 Number 属性。有关参考,请参阅 Vue Web Component Prop 文档

在您的示例中,

:prop="..."
语法是 Vue 特定的,不适用于标准 Web 组件。将
:students="..."
替换为
students="..."
并通过
props.students
手动解析
JSON.parse
字符串,将其转换为对象/数组。

例如

<my-web-component students='[{"name":"John","age":18},{"name":"Jane","age":20}]'></my-web-component>
customElements.define('students-list', defineCustomElement({
  props: {
    students: {
      type: String // change to String
    }
  },
  setup(props) {
    return {
      students: JSON.parse(props.students),
    };
  },
  mounted() {
    console.log("array", this.students)
  }
}));
© www.soinside.com 2019 - 2024. All rights reserved.