Skip to content
Advertisement

How to write method in vuejs using js code?

My codepen link https://codepen.io/santoshch/pen/LYWPMQy

export default {



    data() {
        return {
            expanded: false,
        };
    },




    methods: {

        var checkList = document.getElementById('list1');
        checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
          if (checkList.classList.contains('visible'))
            checkList.classList.remove('visible');
          else
            checkList.classList.add('visible');
        }

    },
};
var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
}

Facing an issue, when trying to convert the js code to vuejs. in the method i tried writting the js code. but getting error.

Advertisement

Answer

Here is the code from plain JS to Vue2 https://codesandbox.io/s/peaceful-http-2n9y7?file=/src/components/SelectionBox.vue

  1. The onclick event in JS can be translated to @click in Vue
checkList.getElementsByClassName('anchor')[0].onclick
// to
<span class="anchor" @click="anchorOnClick">Select Fruits</span>
  1. methods contain function
methods: {
   // function
   anchorOnClick: function (event) { 
     // do something
   }
}
  1. Using expanded variable to control .visible class
<div
    class="dropdown-check-list"
    :class="{ visible: expanded }" // binding class
    tabindex="100"
>
   ....
</div>


anchorOnClick: function (event) { 
    this.expanded = !this.expanded;
}

Binding class reference: https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement