【问题标题】:change button while pressing it with vue.js使用 vue.js 按下按钮时更改按钮
【发布时间】:2018-03-10 16:31:11
【问题描述】:

基本上我想要做的是单击我的按钮并立即隐藏此按钮并使其出现另一个。

我的两个按钮是:

<button @click="" value="Add to favorites" style="font-weight: 700;color:#428bca;margin-left:30px;height:30px;border-radius:4px" name="favorites">Add to favorites</button>

<button @click="" value="Delete from favorites" style="font-weight: 700;color:#428bca;margin-left:30px;height:30px;border-radius:4px" name="delete" v-if="show">Delete from favorites</button>

请我只需要 vue.js 的解决方案

【问题讨论】:

    标签: button vue.js onclick


    【解决方案1】:

    您可以通过属性via v-show 调节每个button 的显示。 (在下面的演示中,使用了isFavorite 属性。)

    然后,在click 事件中,您可以更改此类属性。

    在@click 中直接更改它:

    new Vue({
      el: '#app',
      data: {
        isFavorite: false
      }
    })
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <button @click="isFavorite = true" v-show="!isFavorite">Add to favorites</button>
      <button @click="isFavorite = false" v-show="isFavorite">Delete from favorites</button>
    </div>

    或者通过方法改变它:

    new Vue({
      el: '#app',
      data: {
        isFavorite: false
      },
      methods: {
        toggleFavorite() {
          this.isFavorite = !this.isFavorite;
        }
      }
    })
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <button @click="toggleFavorite" v-show="!isFavorite">Add to favorites</button>
      <button @click="toggleFavorite" v-show="isFavorite">Delete from favorites</button>
    </div>

    或者,如果您认为它会提高代码的可读性,请使用多种方法:

    new Vue({
      el: '#app',
      data: {
        isFavorite: false
      },
      methods: {
        addToFavorites() {
          this.isFavorite = true;
        },
        deleteFromFavorites() {
          this.isFavorite = false;
        }
      }
    })
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <button @click="addToFavorites" v-show="!isFavorite">Add to favorites</button>
      <button @click="deleteFromFavorites" v-show="isFavorite">Delete from favorites</button>
    </div>

    【讨论】:

    • 还有一个问题,你如何在@click="" 上插入两个函数?
    • 像这样:stackoverflow.com/questions/49209834/…(我是那个回答那个的人,顺便说一句:)
    • 这是在某处保存(和加载)isFavorite 数据的问题。按钮将根据其值进行操作。
    • 不要操纵模板(&lt;html&gt; 部分)。让 PHP 设置 data 部分。比如:new Vue({ el: '#app', data: { isFavorite: &lt;?= $favorite == 1 ? 'true' : 'false ?&gt; }, /* ... */ }
    • 添加生成页面的 PHP 代码。您需要进行一些服务器端更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    相关资源
    最近更新 更多