I want to show the update button when the userId matches with one of the previous users & if the userId & one of the previous users doesn't match then it will show the submit button.
I am trying this way---
new Vue({
el: '#app',
data: function() {
return {
userId:1,
previousUsers:[1,2],
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(previousUser,i) in previousUsers" :key="i" >
<button v-if="previousUser == userId" @click="update">Update</button>
<button v-if="previousUser == !userId" @click="add">Submit</button>
</div></div>
In my way the submit button doesn't show if I change the userId to "3". How to solve this?
CodePudding user response:
You are looping through all the previous users and making comparisons with the current user, so you will display one button for each user. If this is your intent you are just writing the second condition in a wrong way: instead of previousUser == !userId
it should be previousUser != userId
, but this way changing the userId
to 3
will make the program render 2 submit buttons, because each previous user you are cycling through is different from the current user id.
Instead, if you want to show just ONE button, and the button should be update
if userId
is in the previous user ids array and submit
otherwise, I suggest you to use a computed
property to decide which button to render, and not to use a v-for
. For example:
new Vue({
el: '#app',
data: function() {
return {
userId:1,
previousUsers:[1,2],
}
},
computed: {
isUserInPreviousUsers() {
return this.previousUsers.indexOf(this.userId) >= 0;
}
}
});
<button v-if="isUserInPreviousUsers" @click="update">Update</button>
<button v-else @click="add">Submit</button>