Tips for creating a VueJS method using JavaScript code?

Check out my codepen link here

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');
}

Encountering an issue while attempting to convert the JavaScript code to Vue.js. I tried writing the JavaScript code in the method, but I am getting an error.

Answer №1

Check out the conversion from plain JS to Vue2 with this code snippet: Vue Conversion Code

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


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

Learn more about binding HTML classes in Vue here: Vue Class Binding Reference

Answer №2

Discover the solution below, including a toggle feature and instructions on managing data binding for the input fields:

<template>
  <div>
    <div id="list1" class="dropdown-check-list" tabindex="100" :class="fruitsListvisible ? 'visible' : ''">
      <span class="anchor" @click="toggleFruitList">Select Fruits</span>
      <ul class="items">
        <li><label for="Apple"><input v-model="selectedFruits" id="Apple" value="Apple" type="checkbox" />Apple</label></li>
        <li><label for="Orange"><input v-model="selectedFruits" id="Orange" value="Orange" type="checkbox" />Orange</label></li>
        <li><label for="Grapes"><input v-model="selectedFruits" id="Grapes" value="Grapes" type="checkbox" />Grapes </label></li>
        <li><label for="Berry"><input v-model="selectedFruits" id="Berry" value="Berry" type="checkbox" />Berry </label></li>
        <li><label for="Mango"><input v-model="selectedFruits" id="Mango" value="Mango" type="checkbox" />Mango </label></li>
        <li><label for="Banana"><input v-model="selectedFruits" id="Banana" value="Banana" type="checkbox" />Banana </label></li>
        <li><label for="Tomato"><input v-model="selectedFruits" id="Tomato" value="Tomato" type="checkbox" />Tomato</label></li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fruitsListvisible: false,
      selectedFruits: [],
    };
  },
  methods: {
    toggleFruitList() {
      this.fruitsListvisible = !this.fruitsListvisible;
    },
  },
};
</script>

<style scoped>
  .dropdown-check-list {
    display: inline-block;
  }
  .dropdown-check-list .anchor {
    position: relative;
    cursor: pointer;
    display: inline-block;
    padding: 5px 50px 5px 10px;
    border: 1px solid #ccc;
  }
  .dropdown-check-list .anchor:after {
    position: absolute;
    content: "";
    border-left: 2px solid black;
    border-top: 2px solid black;
    padding: 5px;
    right: 10px;
    top: 20%;
    -moz-transform: rotate(-135deg);
    -ms-transform: rotate(-135deg);
    -o-transform: rotate(-135deg);
    -webkit-transform: rotate(-135deg);
    transform: rotate(-135deg);
  }
  .dropdown-check-list .anchor:active:after {
    right: 8px;
    top: 21%;
  }
  .dropdown-check-list ul.items {
    padding: 2px;
    display: none;
    margin: 0;
    border: 1px solid #ccc;
    border-top: none;
  }
  .dropdown-check-list ul.items li {
    list-style: none;
  }
  .dropdown-check-list.visible .anchor {
    color: #0094ff;
  }
  .dropdown-check-list.visible .items {
    display: block;
  }
</style>


https://codepen.io/jeremykenedy/pen/yLMBwBP

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Explore the wonders of our solar system using three.js!

I am embarking on my first project using three.js to create a miniature solar system consisting of 1 star, 2 planets, and 1 moon orbiting each planet. As a beginner to both three.js and JavaScript in general, I am eager to learn. Currently, I have success ...

Creating a jar file for ReactJS in JHipster version 7.1.0

I'm currently working on developing a straightforward app using JHipster. The process involves creating the app by running $jhipster Once the initial setup is complete, I proceed to add some entities by executing $jhipster jdl jhipster-jdl.jdl I ...

javascript: restrict the quantity of products

As a beginner in javascript, I am currently working on creating a simple RSS reader. However, I am facing a challenge in limiting the number of feeds to 5 items, especially since the target site may have 100 or more feeds. Here's the code snippet I&ap ...

Dynamic modal in Vue JS with custom components

Within the news.twig file {% extends 'layouts.twig' %} {% block content %} <section class="ls section_padding_bottom_110"> <div id="cart" class="container"> <cart v-bind:materials=" ...

How to efficiently use lunr in typescript?

The Definitely Typed repository demonstrates the importation in this manner: import * as lunr from 'lunr'; However, when attempting to use it in Stackblitz, it results in the following error: lunr is not a function Any ideas on how to resolve ...

Props in Vue components are exclusively accessible within the $vnode

Exploring the realm of Vue.js, I am tasked with constructing a recursive Component renderer that transforms JSON into rendered Vue components. The recursive rendering is functioning smoothly; however, the props passed to the createElement function (code b ...

Dealing with multiple parameters using React Router

I work with two main components: the AddList component and the DetailList component. The functionality I have set up involves a list of AddList components, each containing a button in every li element. When a user clicks on any button, the corresponding ID ...

All you need to know about the impressive world of HTML5

When the server sends coordinates for a shape like a rectangle, rhombus, circle, trapezium, or polygon and I am uncertain about which one will be received, how should I decide on the figure to draw on the canvas using the Angular framework? ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

Navigate to a different page in NextJs and initiate a smooth scrolling effect using the react-scroll library

Utilizing the Next.js Link element in my React application: import Link from 'next/link'; Along with buttons that scroll to a specific element when clicked using: import { Link } from 'react-scroll'; https://www.npmjs.com/package/reac ...

Strategies for capturing the click event on a particular mesh within a group

Currently, I am working with a set of circle geometry elements that are arranged on the vertices of an icosahedron element. I am looking to trigger a click event on each individual circle element using jQuery. Can you provide guidance on how to implement j ...

AngularJS: Understanding the 'controller as' syntax and the importance of $watch

Is it possible to subscribe to property changes when using the controller as syntax? controller('TestCtrl', function ($scope) { this.name = 'Max'; this.changeName = function () { this.name = new Date(); } // not working ...

Which hook should be implemented for automatically updating stock levels after a successful payment on WooCommerce?

When working with WooCommerce, I have implemented my own custom payment method using javascript code. I have successfully retrieved the total amount and passed it to my payment system using the following PHP code: <?php $GLOBALS['cart_total'] ...

Refreshing data from firebase on each route change

I created an Angular service that retrieves items from Firebase using snapshotChanges and returns them. In my component, I subscribe to the data and store it in an array. I then display the data in cards using ngFor. However, whenever I navigate between p ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Top recommendation for preventing memory or performance problems associated with binding a significant amount of DOM elements to a click event

Currently, I am experimenting with different methods using Chrome Dev Tools, although I do not consider myself an expert in JavaScript for modern browsers. Therefore, I am seeking additional feedback to enhance my testing process. I am dealing with a page ...

No data returned when fetching with server-side rendering (SSR) requested

Seeking suggestions on how to implement loading items via API and server-side rendering. My SSR is set up using Express and Babel. Below is the component in question: class MyApp extends Component { constructor(props) { super(props) th ...

ReactNative: When attempting to navigate, a TypeError occurred - this.props.navigation.navigate is not a function

It's confusing to see how this issue is occurring, even though all props have been properly typed. The goal is to pass the navigator to the bottom bar component in order to navigate onPress. Initially, I define the props interface: export interface B ...

Click the JavaScript button to activate the delete function

Imagine an interactive HTML table where a user can easily delete rows by either selecting a row and pressing the delete key on their keyboard or by clicking a designated delete button. This functionality ensures a smooth and intuitive user experience. Se ...

Obtaining multiple divs with identical class names within a specific container

If we have the following HTML code: <div id='m1'> <div class="c"></div> <div class="c"></div> <div class="c"></div> </div> <div id='m2'> <div class="c"></div> <div ...