首页 > 解决方案 > 在同一个模板 vue.js 中重用同一个搜索组件

问题描述

我有正常的搜索输入,女巫会搜索并显示一些结果。这工作正常,我需要克隆这个搜索输入并在同一个组件中再次使用它。

<input class="search ml-2" type="search" placeholder="Search" v-model="search">

js:

 data() {
            return {
                hubs: [],
                search: '',
            }
        },
computed: {
    filteredList: function () {
        return this.hubs.filter((hub) => {
            return hub.name.toLowerCase().includes(this.search.toLowerCase());
        })
    }
},

我的目标是克隆该搜索并显示与先前搜索不同的结果,我该怎么做?我可能需要克隆此搜索输入两次以上。

第二个这样的输入将独立工作,应该返回不同的结果。

标签: vue.jsvuejs2

解决方案


我不确定我是否在关注你,但我举了一个例子来说明你可能想要做什么。

如果您希望它可重用,最好将数组作为 a与要搜索的对象prop一起传递。key

下面是一个带有演示的例子。

<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/


推荐阅读