Guide to creating an Event using Composition API in Vue3

I am currently implementing this feature within a vue3 component:

<template>
    <div class="hamburger-toggle" @click="toggle" :class="{ nav__open: isActive }">
</template>

<script>
export default {
  name: "navbar",
  data() {
    return {
      isActive: true
    }
  },
  methods: {
    toggle: function () {
      this.isActive = !this.isActive;
    }
  }
}
</script>

How should I approach this using the composition api?

Here is my unsuccessful attempt:

<script>
export default {
  props: {
    isActive: false
  },
  setup(props) {
    function toggle(props) {
      props.isActive = !props.isActive;
    }
  }
}
</script>

Answer №1

If you're using the composition API in Vue, remember to replace the data function with ref or reactive and return your functions/reactive data like this:

<template>
    <div class="hamburger-toggle" @click="toggle" :class="{ nav__open: isActive }">
</template>

<script>
import { ref } from "@vue/reactivity";
export default {
  name: "navbar",
  setup() {
    const isActive = ref(true)
    const toggle = () => {
      isActive.value = !isActive.value
    }
  return { isActive, toggle }
}
</script>

Answer №2

With a simplified code snippet, you can achieve the same functionality:

<template>
  <div @click="isActive = !isActive"> ... </div>
</template>

<script setup>
import { ref } from "vue";
const isActive = ref(true)
</script>

To learn more about the <script setup>, click here.

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

Steer clear of directly modifying a prop in Vue.js to prevent errors

I have developed a custom DateField component. It is functioning properly but I am encountering an error message stating Avoid mutating the prop 'value'. This error occurs when I close the menu by clicking the Cancel button or by clicking outside ...

Understanding Json data using Jquery

I am currently learning about Jquery, Ajax, and JSON but I am having difficulty with parsing Json data. Despite researching extensively on stackoverflow Parsing JSON objects for HTML table Access / process (nested) objects, arrays or JSON Parse JSON in ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Using Typescript to define unions with multiple callback types

While in the process of converting my code to TypeScript, I encountered a dilemma. I created a generic foreach function that can handle arrays and objects, with different types of callbacks for iteration. However, I'm unsure how to specify the type wh ...

Managing memory and CPU resources in NodeJS while utilizing MongoJS Stream

Currently, I am in the process of parsing a rather large dataset retrieved from MongoDB, consisting of approximately 40,000 documents, each containing a substantial amount of data. The dataset is accessed through the following code snippet: var cursor ...

Ways to pass a message from index.html to a Vue.js 3 instance

Picture this scenario: You have a Vue index.html file that also loads a custom script: <!DOCTYPE html> <html lang="en"> <head> ... ... <script type="text/javascript"> languagePluginLoader.then(fun ...

Is it possible in Angular to first escape HTML strings and then add HTML markup?

Working with a search form in Angular that pulls data from a database and includes an array of strings, I implemented a pipe to highlight the search query in the results by wrapping it with <mark></mark>. This feature has been quite useful so f ...

Ensuring that jQuery(document).ready(function() contains the appropriate content

Recently, I've been attempting to integrate a javascript gallery into my WordPress site. However, I'm encountering some confusion regarding what needs to be included in the .ready(function) to successfully run the gallery. The original jQuery fun ...

Is it possible to display a thumbnail image in a separate full-sized window by using CSS or JavaScript?

I am currently utilizing a program called WebWorks 2020.1 that automatically creates <img> tags from my FrameMaker source input when published to DHTML. Unfortunately, I do not have the ability to directly modify the HTML <img> or <a> tag ...

Retrieving Specific Text Data from Formik Dropdown<option>

I have implemented a reusable Material-UI select component in my project based on the code snippet provided in a tutorial. The SelectWrapper component is used to create a select dropdown with various options: import React from 'react'; import { T ...

Issue with JavaScript Variable Not Reflecting Changes in Progress Bar

I'm in the midst of developing a game and have incorporated a progress bar to facilitate the incrementation of certain values on my HTML page. However, once the progress bar hits 100%, it updates the cost and level only once. After that initial update ...

Retrieving event.data from the input handler on a textarea element

I've spent the past few days researching this issue. Here's some context to help explain the goal: I have a textarea and I want it to detect special characters (like @) that I define as part of a dictionary. It should then display an autocomple ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

Guide on configuring a monorepository for Vue ecosystem using NX

Is there a way to integrate monorepo tools like NX with Vue 3? I came across an unofficial repository that can be added to NX to work with Vue, but the support is lacking. Are there any other packages that officially support Vue and Vite integration? Here ...

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...

Import a fixed JSON document in Webpack

In the code I have, there is a construction that looks like this: var getMenu = function () { return window.fetch("portal/content/json/menu.json").then(function (data) { return data.json(); }); }; I attempted the following in my webpack.c ...

Is there a way to delete a field from a JSON object using JavaScript?

Searching for a way in Node.js to eliminate the date and operation fields from the database. Any suggestions on how to do this? Currently, all fields are being transferred to the FE. The collection pertains to MongoDB. collection.find({'recordType&ap ...

"Seamless responsiveness in design with jQuery, but encountering compatibility issues

My usage of jQuery is quite basic to ensure that elements are properly positioned when they are moved: function ipad() { var width = jQuery(window).width(); if (width < 1200 && width >= 768){ //if tablet jQuery('.mobbut').css(&apo ...

Creating objects in JavaScript using Object.create can sometimes cause issues in Internet

I have been working on software development for SharePoint 2013, specifically dealing with overriding SharePoint's file previewer (changing filepreview.debug.js to myfilepreview.debug.js). Unfortunately, we have encountered a problem with IE8, while e ...