Skip to content
Advertisement

Prevent user to change checkbox value conditionally in Vue Js?

** How to prevent user to edit check-box value if user doesn’t have permission. I want to display model if user doesn’t have permission to edit. So, disabling input box wont work**

Vue.component('edit-deal', 
     data: function(){
        showDeal: true,
        hasPermission: false
},
template:`
    <label>Show deals </label>
    <input type="checkbox" v-model="showDeal">
`
)

Advertisement

Answer

You can set an event listener on click of the checkbox, and if there’s no permission, emit an event to the parent component to show a modal:

const editdeal = Vue.component('edit-deal', {
  template: '#edit-deal',
  data: () => ({ showDeal: true, hasPermission: false }),
  methods: {
    checkPermission(event) {
      if(!this.hasPermission) {
        this.$emit("show_modal");
        event.preventDefault();
      }
    },
  },
});

new Vue({
  el: '#app',
  components: { editdeal },
  data: () => ({ showModal: false }),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div><editdeal @show_modal="showModal=true"/></div>
  <div v-if="showModal">No Permission Modal</div>
</div>

<template id="edit-deal">
  <div>
    <label>Show deals </label>
    <input type="checkbox" v-model="showDeal" @click="checkPermission">
  </div>
</template>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement