【问题标题】:better way to handle multiple emits in vue在 vue 中处理多个发射的更好方法
【发布时间】:2021-04-27 12:53:18
【问题描述】:

如果我进入一个页面来用菜单做一些魔术,我有任务要做,我有一个解决方案,但它似乎非常静态,对于像 vue 或 quasar 这样花哨的现代事物来说,它的代码太多了。

在每个组件上我需要发出一个事件,例如:

this.$root.$emit('category-one--name')

为了接收发射事件并处理我使用这个的东西:

this.$root.$on('category-one--name', this.setSelectBox1)
this.$root.$on('category-otherone--name', this.setSelect2)
this.$root.$on('category-more--name', this.setSelectBox3)
this.$root.$on('category-somemore--name', this.setSelect4)
this.$root.$on('category-ansoson--name', this.setSelectBox5)

然后我处理以下内容:

setSelectBox1() {
  this.model = this.categories[1]
},
setSelectBox2() {
  this.model = this.categories[2]
},

有没有更好的方法,例如给发出的事件一个 Id 或其他东西,然后在一个方法中迭代所有内容,而不仅仅是重复代码?

谢谢

【问题讨论】:

    标签: vue.js quasar


    【解决方案1】:

    Emit function 接受一个值作为第二个参数,所以试试这个:

    this.$root.$emit('category-change', this.name);
    

    然后:

    this.$root.$on('category-change', this.setSelectBox);
    
    
    setSelectBox(category) {
      // set model here
    },
    

    【讨论】:

    • @CamelCase 就像在这个答案中一样。您应该传递参数(可能是字符串或对象)并根据它做出后续决策。
    猜你喜欢
    • 2011-11-24
    • 2017-12-07
    • 2010-09-25
    • 2016-07-11
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多