Reputation: 63
I'm creating a multiselect in Vue js, but wat i dont understand is how can i get multiple instance of the component with each a different initial selected value (v-model). Every component is getting the same initial value because of the selected data on the parent. Should i also use props here instead of v-model? or should i move the data object from the parent to the component itself?
Wat i want
Component one should have initial select "{ id: "0", text: "One"}" and
Component two should have initial select "{ id: "1", text: "Two"}"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<div id="app">
<multi-select v-model="selected" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>
<multi-select v-model="selected" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("multi-select", {
props: ["options", "value"],
template: `
<div>
<div v-for="option in selectedOption">{{ option.text }}</div>
<hr>
<div v-for="option in options">{{ option.text }}</div>
</div>
`,
computed: {
selectedOption() {
return this.value;
}
}
});
new Vue({
el: "#app",
data: {
selected: [{ id: "0", text: "One"}],
}
})
</script>
</body>
</html>
Upvotes: 2
Views: 1885
Reputation: 668
v-model means the selected value, pay attention that you are assigning both multiselects to the same variable.
a possible solution is creating another variable, lets say selector2
and selector1
and assigning your v-model accordingly.
data: {
selected1: [{ id: "0", text: "One"}],
selected2: [{ id: "1", text: "Two"}],
}
and on assignment
<div id="app">
<multi-select v-model="selected1" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>
<multi-select v-model="selected2" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>
</div>
Upvotes: 1
Reputation: 4879
Pass index as props and your child component can use this index to decide the default value.
v-bind:index="0"
v-bind:index="1"
Upvotes: 2