Home > Enterprise >  How do I reverse a string by selecting the option from drop down box in vue.js?
How do I reverse a string by selecting the option from drop down box in vue.js?

Time:07-19

In the below example, if I use the "v-on:click" for button then it works well but when I try this on dropdown option then it doesn't work. What I mean is when I select "reverseme" option then it should reverse item1.

<!DOCTYPE html>
<html>
<head>
  <title>Vue Js in Reverse Array Using Function Example - Laratutorials.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div  id="app">
    <p>item 1 = {{ item1 }}</p>
    <select >
        <option value="">Select Options</option>
    <option value="reverseme" v-on:click="myFunction()" >reverseme</option>
    <option value="dontreverse1">dontreverse 1</option>
    <option value="dontreverse2">dontreverse 2</option>    
    </select>
</div>
<script>
    new Vue({
   el: '#app',
     
     data: { 
         item1:[15, 11, 10, 8, 20, 13]
     },
     
      methods:{
       myFunction: function () {        
           this.item1.reverse();    
       }   
      }
   });
   </script>    
</body>
</html>

CodePudding user response:

As @D.Schaller mentioned, the option tag does not support the onClick event, although you can check what option was selected in the @change handler and based on that, decide if you want to reverse or not the array.

new Vue({
  el: '#app',

  data: {
    item1: [15, 11, 10, 8, 20, 13]
  },

  methods: {
    myFunction(e) {
      if (e.target.value === 'reverseme') this.item1.reverse();
    }
  }
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div  id="app">
  <p>item 1 = {{ item1 }}</p>
  <select  @change="myFunction">
    <option value="">Select Options</option>
    <option value="reverseme">reverseme</option>
    <option value="dontreverse1">dontreverse 1</option>
    <option value="dontreverse2">dontreverse 2</option>
  </select>
</div>

  • Related