"Exploring the power of Vue3's composition API in managing the

Trying to implement an accordion component in Vue 3, but encountering a strange comparison issue.

I'm attempting to execute a function within the accordionitem - specifically the toggle operation. However, despite numerous attempts, I am unable to modify the props value. What could be causing this issue?

My goal is to have multiple toggles when the toggle function is clicked. If not, I want to display only one at a time. There is an example provided in the link below, but I cannot achieve this with Vue 3.

Link

faq.vue

<template>
  <accordion id="hello" :content="exampleData1"></accordion>
  
</template>
<script setup>
import Accordion from "@/components/Accordion.vue";

const exampleData1 = [
 {
  id: 1,
  active: false,
  title: 'Crushing Spirits',
  details: `
      <p>You can crush me but you can't crush my spirit! Are you crazy? I can't swallow that. Who's brave enough to fly into something we all keep calling a death sphere? It doesn't look so shiny to me.</p>
      
    `
 },
 {
  id: 2,
  active: false,
  title: 'Soundtracks',
  details: `
      <p>Ah, the 'Breakfast Club' soundtrack! I can't wait til I'm old enough to feel ways about stuff!</p>
    `
 },
 {
  id: 3,
  active: false,
  title: `The Letter Shaped Like a Man Wearing a Hat`,
  details: `<p>And then the battle's not so bad? You'll have all the Slurm you can drink when you're partying with Slurms McKenzie! Say it in Russian!</p>
    
   `
 }
]

</script>

AccordionItem.vue

<template>
 <dl class="accordion box" role="presentation">
 
</template>

<script setup>
import AccordionItem from "@/components/AccordionItem.vue";

const props = defineProps({
 content: {type: Array, required: true},
 id: {type: String, required: false}
})
</script>

AccordionItem.vue

<template>
 <div :id="groupId + '-' + item.id" class="accordion-item" :class="{'is-active': item.active}">
  <dt class="accordion-item-title">
   <button @click="toggle" class="accordion-item-trigger">em>Togglegt;
   
   </button>
  </dt>
  {{ item.active }}
  <transition
      name="accordion-item">
  </transition>
 </div>

</template>

<script setup>
const props = defineProps({
 item: {type: Object, required: true},
})

function toggle(event) {
 props.item.active = !props.item.active
}


function startTransition(el) {
 el.style.height = el.scrollHeight + 'px'
}

function endTransition(el) {
 el.style.height = ''
}
</script>


Answer №1

To ensure your array is reactive, use either ref or reactive. As mentioned in the comments, emit an event from the child component and listen for it in the parent component. For a visual demonstration, check out this demo HERE

Answer №2

It is not possible to modify props within the component that initially defined them. Here are some alternatives:

  1. Trigger an event to inform the parent component to update the value.
  2. Store the data in a central location and access it from there instead of passing it as a prop.

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

Navigating between child nodes in an HTML drop down list with multiple options and hierarchical structure

Hey there! I am looking to create a unique HTML hierarchy drop-down menu. It will have multiple levels or options, with each option having the potential for child nodes. When an option has child nodes, an arrow will appear next to it. Clicking on this ar ...

When making a request through local apache, the POST method is switched to GET

I've been attempting to send a post request using the code below. However, the request is being sent as a GET instead of POST. How can I resolve this issue? $.ajax({ url: 'https://www.exampleurl.com', method: 'POST', h ...

The value of the progress bar in Bootstrap Vue cannot be retrieved using a function

I have implemented a progress bar using Bootstrap Vue. Here is the HTML code: <b-progress :value="getOverallScore" :max=5 variant="primary" animated></b-progress> The getOverallScore function calculates an average value based on three differe ...

Expanding functionality: Steps to integrating a new endpoint into your AWS Amplify Express Server

I have created a REST express server using Amplify. Attempted to include two additional endpoints: // incorporating serverless express app.post('/myendpoint', function(req, res) { console.log('body: ', req.body) res.json(req.body) ...

Obtaining JSON data in an Angular service: A beginner's guide

My JSON file has the following structure: { "user": [ { "id": 0, "data": [ { "userName": "iheb", "useremail": "", "userPassword": "kkk" } ], "questionnaireListe": [ { ...

Winning awards through the evaluation of possibilities

I became intrigued by the idea of using a chance algorithm to simulate spinning a wheel, so I decided to create some code. I set up an object that listed each prize along with its probability: const chances = { "Apple" : 22.45, & ...

What is the best way to ensure the submenu is visible on every menu when the cursor hovers over it

I am currently working on implementing a drop-down menu using react.js. I have been following a tutorial but encountered an issue when trying to add a submenu to the menu items. Instead of the submenu appearing only for the specific menu item hovered over, ...

Angular Bootstrap uibModal is failing to resolve attributes

Issue with Roles in AngularJS Bootstrap uiModel var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', size: 100, resolve: { roles: f ...

Accessing and displaying all states in $stateProvider using AngularJS and ui-router

Here's a simple question: how can I find all instances of $stateProvider.state in my app.js, which is my AngularJS config file? In the past with ngRoute, I could achieve this by using a similar approach in my .run() block: .run(function ($route) { ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Elements are randomly glitching out with CSS transitions in Firefox

Chrome is working perfectly for me, but when I switch to Firefox it behaves differently than expected I am attempting to create a simple animation (utilizing transitions) that continuously runs on mouseover and smoothly returns to the starting position on ...

Display all elements on a webpage using Javascript without the need for scrolling

I'm looking for a way to ensure all items on a webpage load immediately, without having to scroll down multiple times before running a script to find a specific item. Is there a method to have all items load at once without the need to manually scroll ...

What is the process for generating a collection of objects in a Mongoose Model?

I am currently working on creating a structure similar to this: var User = mongoose.model('Clicker', totalClicks: [ {type: Number, default: 0}, {type: Number, default: 0} ], I have explored various documentation resources related to ...

Error: Invalid hook calls detected in React using Material-UI components

Hey there! I'm relatively new to the world of React and I've been tackling an issue with implementing the SimpleBottomNavigation component. Unfortunately, I keep running into an error message that says: "Uncaught Error: Invalid hook call. Ho ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Looking for assistance with arranging and managing several containers, buttons, and modals?

My goal is to create a grid of photos that, when hovered over, display a button that can be clicked to open a modal. I initially got one photo to work with this functionality, but as I added more photos and buttons, I encountered an issue where the first b ...

What are some strategies for breaking down large components in React?

Picture yourself working on a complex component, with multiple methods to handle a specific task. As you continue developing this component, you may consider refactoring it by breaking it down into smaller parts, resembling molecules composed of atoms (it ...

Struggling to incorporate Three.js into a Vue project utilizing modules

Incorporating TrackballControl.js from the example folder of the npm package for Three.js into my Vue project using Webpack has been a challenge. After researching, I stumbled upon this helpful solution on Github. https://i.sstatic.net/KqSF6.png To imple ...

JavaScript Library function in Angular Component throwing Type Error: Function is Not Recognized

I created a custom Javascript library to group together essential functions that many Angular Components require. The library called calcs.js includes functions like this: function calculateCosts(object) { do some stuff..... return answer; } To use t ...

Troubleshooting AngularJS form submission with missing data

Is there a way to modify AngularJS to save form data into a database using PHP as the backend? Below is the HTML form code: <form ng-submit="newContactSubmit()"> <label>FirstName<input type="text" name="contact_firstname" required n ...