1

Im trying to open my modal in VueJS only when i click on the "New" option, how can i do that?

      <select v-model="input.des"   @change="$refs.modalName.openModal()">              
           <option value="A">A</option>
            <option value="B">B</option>
           <option value="New">New</option>
          </select>



openModal() {

  this.show = true;
  document.querySelector("body").classList.add("overflow-hidden");
},

2 Answers2

2

The easiest way for that would be to watch for option changes:

new Vue({
  el: '#app',

  data() {
    return {
      input: {
        des: ''
      },

      show: false
    }
  },

  methods: {
    openModal() {
      this.show = true;
      document.body.classList.add('overflow-hidden');
    }
  },

  watch: {
    'input.des'(val) {
      if (val === 'New') {
        //this.$refs.modalName.openModal();

        this.openModal();

        alert('Modal opened');
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>

<div id="app">
  <select v-model="input.des">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="New">New</option>
  </select>
</div>
Yom T.
  • 8,760
  • 2
  • 32
  • 49
1

You can get the selected value of the selected option from event.target. You can find more on that in the answers here.

Change your code to:

<select v-model="input.des" @change="$refs.modalName.openModal">              
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="New">New</option>
</select>

openModal(event) {
    if (event.target.value == "New") {
        this.show = true;
        document.querySelector("body").classList.add("overflow-hidden");
    }
},
anpel
  • 931
  • 6
  • 16
  • I was using this and it works. However, I once new is selected - if we want to allow clicking on new again to open the modal (to edit some form), it will not open modal unless we change the select option to something else and come back to new. Is there a way to handle it? – rsram312 May 19 '23 at 14:19