Reputation: 87
I have normal search input witch will search and display some results. This is working fine, i need to clone this search input and re-use it again in the same component.
<input class="search ml-2" type="search" placeholder="Search" v-model="search">
The js:
data() {
return {
hubs: [],
search: '',
}
},
computed: {
filteredList: function () {
return this.hubs.filter((hub) => {
return hub.name.toLowerCase().includes(this.search.toLowerCase());
})
}
},
My goal is to clone that search and show different result then the previous search, How can i do that ? I might need to clone this search input more then twice.
The second seuch input would work independent, should return different result.
Upvotes: 0
Views: 437
Reputation: 3653
I'm unsure if I'm following you, but I made an example showing what you probably want to do.
If you want it to be reusable it's better if you pass your array as a prop
together with key
in it's objects that's to be searched.
Below is an example with demo.
<div id="app">
<search :data="todos" search-key="text"></search>
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos">
<label>
<input type="checkbox"
v-on:change="toggle(todo)"
v-bind:checked="todo.done">
<del v-if="todo.done">
{{ todo.text }}
</del>
<span v-else>
{{ todo.text }}
</span>
</label>
</li>
</ol>
<search :data="todos" search-key="text"></search>
</div>
Vue.component('search', {
data() {
return {
userInput: '',
results: []
}
},
props: { data: Array, searchKey: String },
template: `<div><input type="text" placeholder="Search..." v-model="userInput" class="form-control form-border-input" @input="search" />
<ul><li v-for="result in results">{{result.text}}</li></ul>
</div>`,
methods: {
search() {
this.results = this.data.filter(item => item[this.searchKey].toLowerCase().includes(this.userInput.toLowerCase()));
}
}
})
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
]
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
http://jsfiddle.net/eywraw8t/358621/
Upvotes: 1
Reputation: 367
You'll need a separate search
property to hook up to the v-model of the second input.
You should probably also convert your computed filteredList
property into a method that accepts a search query string. That way you can reuse it for both the inputs.
Upvotes: 0