【问题标题】:Binding method to an option in a component in vue.js将方法绑定到 vue.js 中组件中的选项
【发布时间】:2019-03-13 06:26:30
【问题描述】:

我是 Vue 的新手,正在使用一个 litebox 组件,我想对其进行一些自定义,以便灯箱库根据按下的按钮从不同的图像开始。我已经通过使用我绑定到 litebox 组件中的一个选项的点击事件成功地解决了这个问题。因为我是 Vue 的新手。我只是想知道这是否是解决此类问题的好方法,或者是否有更好的方法?

<template>
  <div id>
    <button type="button" @click="show(); start1();">Show Litebox start 1</button>
    <button type="button" @click="show(); start2();">Show Litebox start 2</button>

    <vue-litebox v-if="showLitebox" :startAt="start" :items="images" @close="hide"></vue-litebox>
  </div>
</template>

<script>
import VueLitebox from "vue-litebox";

export default {
  components: { VueLitebox },
  data() {
    return {
      images: [
        "https://placekitten.com/400/400",
        "https://placekitten.com/400/401",
        {
          title: "My image title",
          src: "https://placekitten.com/400/402"
        }
      ],
      showLitebox: false,
      start: 0
    };
  },
  methods: {
    show() {
      this.showLitebox = true;
    },
    hide() {
      this.showLitebox = false;
    },
    start1() {
      this.start = 1
    },
    start2() {
      this.start = 2
    }
  }
};
</script>

这里是代码沙箱上的代码: https://codesandbox.io/s/9ok4y6lopo?fontsize=12

【问题讨论】:

  • 一般的@click 方法很好,但链式方法(使用;)则不太好。为什么不改为show(x),然后在show 中做this.start = x

标签: vue.js vue-component


【解决方案1】:

模板应该尽可能地无逻辑,此外,没有必要以这种方式链接方法,因为您始终可以将参数传递给方法,如下所示:

// in your template
<button
  type="button"
  @click="show(1)"
>
  Show Litebox start 1
</button>

// in methods section
show (start = 1) { // defaults to 1
  this.show = true;
  this.start = start;
}

顺便说一句,对于 vue-litebox 组件 (see documentation),v-show 似乎比 v-if 更好。

【讨论】:

  • 感谢您的解决方案!实际上,由于某种原因,v-show 在这种情况下并没有真正起作用,所以我需要 v-if。您可以通过打开和关闭不同图像来更改代码沙箱来进行测试。
猜你喜欢
  • 2019-07-22
  • 2021-04-21
  • 2019-10-15
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多