【问题标题】:Vue.js shared input data across componentsVue.js 跨组件共享输入数据
【发布时间】:2020-08-08 06:40:41
【问题描述】:

我有 4 个显示不同数据的组件。在每个组件中,我都有一个包含输入的导航栏,我用它来过滤组件中的数据,如下所示:

computed: {
  filteredItems() {
    if (this.search !== '') {
      return this.allManufacturers.filter(item => {
        return item.id.toUpperCase().startsWith(this.search.toUpperCase()) === true
      })
    }
    return this.cars.filter(item => {
      return item.id.toUpperCase().startsWith(this.search.toUpperCase()) === true
    })
  },
},

计算的属性在 4 个组件中是不同的。 我想将导航栏移动到一个组件并使用导航栏中的输入进行过滤,而不是在每个组件中复制代码

【问题讨论】:

    标签: javascript vue.js filter vuejs2 vue-component


    【解决方案1】:

    创建一个导航栏组件,它将$emit 一个包含搜索值的search 事件。它只有一个模板:

    <template>
      <div>
        <input @input="$emit('search', $event)" />
      </div>
    </template>
    

    您可以在任何其他组件中使用它,如下所示:

    <template>
      <div>
        <navigation @search="newSearch($event.target.value)"></navigation>
        {{ filteredItems }}
      </div>
    </template>
    
    data() {
      return {
        search: ''
      }
    },
    computed: {
      filteredItems () {
        if (this.search !== '') {
          return this.allManufacturers.filter(item => {
            return item.id.toUpperCase().startsWith(this.search.toUpperCase()) === true
          })
        }
        return this.cars.filter(item => {
          return item.id.toUpperCase().startsWith(this.search.toUpperCase()) === true
        })
      },
    },
    methods: {
      newSearch(text) {
        this.search = text;
      }
    }
    

    【讨论】:

    • 谢谢,但是您的解决方案在输入时工作正常,但 v-text-field 没有发送值
    • 到目前为止,您还没有在任何地方提到 Vuetify 或 v-text-field。为此,将其更改为:$event.target.value$event
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2019-08-14
    • 2019-08-18
    • 2016-07-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多