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