change button while pressing it with vue.js

我的梦境 提交于 2021-02-07 10:15:41

问题


Basically what i want to do is clicking my button and immediately hide this button and make appear another.

My two buttons are:

<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>

Please i need a solution only with vue.js


回答1:


You can condition the exibition of each button through a property via v-show. (In the demos below, the isFavorite property is being used.)

Then, in the click events you can change such property.

Either change it directly in the @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>

Or change it via a method:

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>

Or, if you think it'd improve the readability of your code, using multiple methods:

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>


来源:https://stackoverflow.com/questions/49211418/change-button-while-pressing-it-with-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!