I Pass an Array of data to a custom component in Vue js and want to have it in a that is defined in my template, but I get an error of Missing required prop: "students". here is my code.
custom Component:
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 {
}
}
}));
and the code I use to call it is:
<students-list classes="col-sm-12" :students = "[{name: 'John'},{name: 'Sarah'},{name: 'Dave'}]"></students-list>
CodePudding user response:
You could try to define a function in your methods like
students() {
return [{name: 'John'},{name: 'Sarah'},{name: 'Dave'}];
},
and switch
:students = "[{name: 'John'},{name: 'Sarah'},{name: 'Dave'}]"
to
:students="students"
CodePudding user response:
As per your code, it seems you are trying to access the array of data from your parent component to child component which is <students-list>
. If Yes, Here you go :
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',
data: {
studentsList: [{name: 'John'},{name: 'Sarah'},{name: 'Dave'}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<studentsList classes="col-sm-12" :students="studentsList"></studentsList>
</div>