【问题标题】:style binding by @click - vue.js@click 的样式绑定 - vue.js
【发布时间】:2019-06-04 08:13:47
【问题描述】:

我正在切换一个元素,当时我想绑定另一个元素的样式。但我不明白如何使用@click 实现这一目标

data(){
    return {
        show:false,
        filterStyle: {
            top: 0,
            background: "#dfe4ea",
            marginTop: "15px",
            marginBottom: "15px",
        },
    }
}

methods: {
    closing(){
        this.show = !this.show
    },
}

<p class="closeMap" @click="closing()">close</p>

关闭下面的 div。

<div v-show="!show"></>

在下面更改样式 div。

<div :style="filterStyle" class="filter"></div>

有人可以给我解释一下吗?

编辑:顺便说一句,正如你所见,我正在绑定我的样式,这没问题。但不是@click... 我想通过@click 绑定这些样式。

【问题讨论】:

  • @click 是一个钩子,允许您在用户单击时运行代码(实际上可以执行任何操作)。这意味着您可以更改 vm 中的属性,从而为单击的元素应用不同的样式。

标签: javascript vue.js vuejs2


【解决方案1】:

不知道你是要在show还是!show上加样式,反正你可以这样实现:

<div :style="show ? filterStyle : null" class="filter"></div>

filterStyle 将仅在 showtrue 时应用

【讨论】:

  • 我会这样做,但我认为如果你愿意,这将是一种更“可读”的方式:&lt;div :class="{ 'filter': !show, 'filterStyle': show }" &gt;&lt;/div&gt;
  • @riesa filterStyle 不是一个类,我认为他希望在这两种情况下(show!show)都将filter 类保留在元素上。当然,这可以通过使用不同的类以更好的方式实现
【解决方案2】:

我猜你可以创建一个计算属性,它会根据this.show 改变:

// Template
<div :style="filterStyle" class="filter"></div>

// Computed property
computed: {
  filterStyle() {
    if (this.show) {
       return {
         top: 0,
         background: '#dfe4ea',
         marginTop: '15px',
         marginBottom: '15px'
       };
    } else {
      return '';
    }
  }
}

您还可以在点击函数中将filterStyle 设置为其他值

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 1970-01-01
    • 2019-06-28
    • 2021-02-22
    • 2020-07-30
    • 2017-02-06
    • 2016-05-16
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多