Ways to integrate vanilla JavaScript with VueJS

I am currently working on implementing a vuejs component and could use some guidance. Can anyone provide assistance on where to place the JavaScript code in order for it to function correctly? As a newcomer to vuejs, I am still uncertain about how to properly set everything up within the script section.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
} 
});
}
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}

.active, .accordion:hover {
background-color: #ccc;
}

.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}

.active:after {
content: "\2212";
}

.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<h2>Accordion with symbols</h2>

<button class="accordion">Section 1</button>
<div class="panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

Thanks!

Answer №1

Within the script tag of your Vue component, you have the flexibility to insert standard JavaScript code. The execution process mirrors that of a typical app.js file.

Answer №2

For those diving into learning Vue, I recommend exploring how to accomplish your desired functionality using Vue's own resources instead of relying on traditional JS event handlers and document selectors.

You can conveniently attach event listeners for common events with the v-on: directive (or @):

<button class="accordion" @click="myClickHandler">Section 1</button>

You can reference other elements using the ref property, accessible in the Vue component under this.$refs:

<div class="panel" ref="myPanel">...

Within your myClickHandler method:

methods: {
  myClickHandler() {
    let panel = this.$refs.myPanel
    ... do stuff ....
  }
}

This is considered "the Vue way" of addressing your issue - eventually becoming efficient and straightforward compared to conventional JS dom selections and event listeners.

I suggest delving deeper into utilizing Vue's tools rather than trying to force native JS and missing out on Vue's simplicity.

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

Developing an animated feature that displays a dynamic count up to the current size of the browser window

I have a script that's able to determine the height and width of my browser window. However, I am facing a challenge in creating a way for these dimensions to count up from zero to their current values upon loading. The desired functionality would be ...

Verify if the user is currently inputting text within a specific range of characters within

I am dealing with a specific issue involving a textarea. By default, this textarea contains a string of any type, but a user is only able to type inside opening and closing brackets. For example, "Leave[]" allows typing within the brackets but not outsid ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

Error encountered when attempting to retrieve posts using Axios: Unexpected symbol detected, expected a comma (25:4)

I've been working on implementing an axios getPosts function, but I keep encountering a syntax error that I can't seem to locate in my code. getPosts = async () => { let data = await api.get('/').then(({ data }) => data); ...

Differences in results occur when JavaScript function declarations are used in both Native browser and Node.js environments

When running the code below, the results differ between Browser and Node.js environments. In the browser, the result is a. In Node.js, the result is b. if (1) { function foo() { return 'a'; } } else { function foo() { return 'b&ap ...

Animation event in CSS3 fails to trigger on Firefox browser

Exploring the potential of CSS3 animation to detect when an input transitions from the enable to disable state, I encountered a challenge specifically in Firefox. Here is the code snippet that showcases the issue: View Demo on jsFiddle HTML: <input t ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Maintain a consistent header height with CSS even when using the calc() function

--dis: calc(var(--max-height) - var(--min-height)); /* @media large{--min-height:13rem}; @media small{--min-height:6.5rem}; --max-height:75vh; */ --percent: calc(var(--scroll-ani) / var(--dis)); /* in js: document.body.style = "--scroll-ani: ...

What is the best way to upload this HTML file to create my own visual representation?

Feeling a bit unsure about which way to go for this problem, I don't have many options at the moment. Lately, I've been diving into Deep Learning and I'm interested in experimenting with Stanford's CS231N's Convolutional Neural Ne ...

Animate an svg icon to follow a designated path as the user scrolls

I am currently working on a project that involves animating a bee svg icon as the user scrolls through the website. The bee starts at the top and fills in a grey color line with pink as the user moves forward, and moves backward as the user scrolls back. Y ...

Interested in generating buttons automatically based on a JSON file

Currently, I am faced with the challenge of creating buttons within a CSS grid without knowing the exact number of buttons that will be populated from a JSON file. The range could vary greatly, from as few as 5 to as many as 55. I am seeking guidance on t ...

I'm wondering how to adjust the index in a loop so that it starts at 1 instead of the standard 0

Currently, I am using a .each function to create a dropdown list. As we know, the index of an array element always begins at 0 in programming. However, for my specific requirement, I need the first value in the dropdown list to start at 1 instead of 0. ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

Issue with the Bootstrap carousel jQuery plugin

Hi everyone, I need some help with creating a multiple items bootstrap carousel. I keep getting an error message that says "#Carousel".carousel is not a function TypeError: "#Carousel".carousel is not a function. Can anyone guide me on how to fix this issu ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

What are the differences between displaying JSON data on a Flask interface compared to a Django interface

Currently, I am looking for the simplest method to display data on a web interface using either Flask or Django (whichever is easier). I already have some sample JSON objects available. Could anyone provide recommendations on how to achieve this and whic ...

Could someone kindly clarify the workings of this jQuery script for me?

I found this code online, but I'm struggling to comprehend its functionality. In order to make any edits for my needs, I need to understand how it operates. The purpose of this script is to close a panel with an upward slide animation when the "x" but ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...

Can anyone tell me what js stands for?

I stumbled upon this snippet of code and am curious about what it does. Is it some sort of array? test = {a: [1,0,0], b:[0,1,0], c:[0,0,1]}; If I wanted to access the array for A specifically, how would I do that? console.log(bases[a]); This results in ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...