Home > Software engineering >  Vue3 composition API accordion menu, problem with showing data
Vue3 composition API accordion menu, problem with showing data

Time:03-20

I try to show the data when it is true, but it doesn't work. I want to make an accordion menu (after clicking on a question, toggle an open property and show the answer if it's true)

Here is code:

<div >
<h1 >Frequently asked questions</h1>
<div >
    <div  v-for="(item, i) in dataBase" :key="i">
      <div  @click="item.open = !item.open">
        <h1>{{item.q}}</h1>
      </div>
      <div  v-show="item.open">
        {{item.d}}
      </div>
    </div>
</div>

And data:

const dataBase = [{
  q: 'How much does it cost?',
  d: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
  open: false,
},
  {
    q: 'How it works?',
    d: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
    open: false,
  }]

Can anyone help and explain why in the console log it changes to true => false and vice versa, but doesn't show the data when it's true? Im new in Vue.

CodePudding user response:

your code is working bro. i runned on my computer.

if you asked 'why true->false and false->'. true and false is boolean variable.

<div  @click="item.open = !item.open">

and this line you did

item.open = !item.open // if item.open is true then here is false.
item.open = !item.open // if item.open is false then here is true.

what is this exclamation(!) in vue ?

!(false) // true
!(true) // false

CodePudding user response:

Your dataBase property is not reactive, you should use ref to make it reactive :

import {ref} from 'vue'
const dataBase = ref([{
  q: 'How much does it cost?',
  d: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
  open: false,
},
  {
    q: 'How it works?',
    d: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
    open: false,
  }])

CodePudding user response:

Your code is working fine. Checkout this : https://codesandbox.io/s/inspiring-jones-rsp2he?file=/src/App.vue

I copied your code & on toggle it shows answer.

  • Related