Кнопка массива переключения Javascript - PullRequest
0 голосов
/ 11 декабря 2018

У меня есть раздел часто задаваемых вопросов на веб-сайте, но он открывается только при нажатии на кнопку.Я хочу открывать и закрывать, когда вы нажимаете.

Вся информация для часто задаваемых вопросов присутствует в Javascript, и все это вызывается с помощью функции v-for.

Я вставляю свойкод ниже, надеюсь, вы поможете мне.

HTML:

<div class="section10">
            <div class="content-container qa-content-container">
                <h2>Frequently asked questions,
                    <br> answered.
                </h2>

                <div class="column">
                    <div class="qanda-div w-col" v-for="(faqs, index) in faq" :key="faqs.questions">
                        <button class="qa-toggle-button w-button" @click="toggle(index)">

                            {{faqs.questions}}
                        </button>
                        <p class="qa-answer" style="none" v-show="faqs.flag">
                            {{faqs.answers}}
                        </p>
                    </div>
                </div>

                <p class="grey qa-moreQ">
                    Got more questions? Ask us
                    <a href="mailto:contact@web.co" class="green">here.</a>
                </p>
            </div>
        </div>

Javascript:

<script>
export default {
    layout: 'noFooter',

    data(){
        return {
            faq: [
                {
                    questions: 'Seriously, free?',
                    answers: "Yes; as an Organiser you don't pay any setup, monthly or annual fees. With Ticketpass you'll recieve 100% of your ticket sales. We organise events too and know how much time and effort you put into them. You shouldn't be paying fees after all that!",
                    flag: false
                },

                {
                    questions: 'How do tickets work?',
                    answers: "When someone registers for your event or purchases a ticket, we'll send them an email with your event details, a booking reference, and a unique QR code. You will be able to check them in online at the event entrance, or if you are old school, you can download and print a beautiful sheet with your attendees' name and the ticket type they bought. Simple!",
                    flag: false
                },

                {
                    questions: 'How do I collect my money?',
                    answers: "As soon as your event ends, we'll process your payment and arrange for it to be transferred to your account. We understand that in some cases you may need to access your sales revenue before the event in order to cover costs, in which case you can apply for early payment by verifying your identity. Note that depending on your bank it can take a few working days for payments to show in your account.",
                    flag: false
                },

                {
                    questions: "If it's free, how can you afford coffee?",
                    answers: "Ticketpass is completely free for organisers, our costs are covered on card payments when attendees purchase tickets.",
                    flag: false
                },

                {
                    questions: 'Do I need to pay any processing fees?',
                    answers: "Nope, we'll take care of them. - Happy days! :)",
                    flag: false
                },

                {
                    questions: 'Can I see an attendees list for my event?',
                    answers: "Yes - you can view and download an attendee list from your event dashboard, where you can also track registrations and keep an eye on ticket sales 24/7.",
                    flag: false
                },

                {
                    questions: 'Can I offer a discount to selected people?',
                    answers: "Yes, you can!  And it's very simple. When creatng your event tickets, in 'advanced settings' you can generate a discount code to share with whoever you like!",
                    flag: false
                },

                {
                    questions: 'Will I be able to message my attendees?',
                    answers: "Yes. If you need to communicate any information or updates you can do so easily through your dashboard.",
                    flag: false
                },

                {
                    questions: 'Can I run private events?',
                    answers: "Absolutely! When you create your event just select 'private' and your event will be hidden from the homepage and search function. You will still have your unique event URL to share it with only the people you want!",
                    flag: false
                },

                {
                    questions: 'What if I have a recurring event?',
                    answers: "Cry... with happiness! Because with one-click you can duplicate your event or enable automatic recurrence ;)",
                    flag: false
                }
            ],
        }
    },

    methods:{
        toggle: function(index){
            for(var i = 0; i < this.faq.length; i++){
                this.faq[i].flag = false;
            }
            this.faq[index].flag = true;
        }
    }
}
</script>

Большое спасибо!

1 Ответ

0 голосов
/ 11 декабря 2018

Это потому, что вы всегда устанавливаете flag на true.Попробуйте инвертировать логическое значение.

this.faq[index].flag = !this.faq[index].flag;

Редактировать: Это один из способов, но не самый лучший.Я обновлю свой ответ.

var example1 = new Vue({
  el: '#example',
  data() {
    return {
      faq: [{
          questions: 'Seriously, free?',
          answers: "Yes; as an Organiser you don't pay any setup, monthly or annual fees. With Ticketpass you'll recieve 100% of your ticket sales. We organise events too and know how much time and effort you put into them. You shouldn't be paying fees after all that!",
          flag: false
        },

        {
          questions: 'How do tickets work?',
          answers: "When someone registers for your event or purchases a ticket, we'll send them an email with your event details, a booking reference, and a unique QR code. You will be able to check them in online at the event entrance, or if you are old school, you can download and print a beautiful sheet with your attendees' name and the ticket type they bought. Simple!",
          flag: false
        },

        {
          questions: 'How do I collect my money?',
          answers: "As soon as your event ends, we'll process your payment and arrange for it to be transferred to your account. We understand that in some cases you may need to access your sales revenue before the event in order to cover costs, in which case you can apply for early payment by verifying your identity. Note that depending on your bank it can take a few working days for payments to show in your account.",
          flag: false
        },

        {
          questions: "If it's free, how can you afford coffee?",
          answers: "Ticketpass is completely free for organisers, our costs are covered on card payments when attendees purchase tickets.",
          flag: false
        },

        {
          questions: 'Do I need to pay any processing fees?',
          answers: "Nope, we'll take care of them. - Happy days! :)",
          flag: false
        },

        {
          questions: 'Can I see an attendees list for my event?',
          answers: "Yes - you can view and download an attendee list from your event dashboard, where you can also track registrations and keep an eye on ticket sales 24/7.",
          flag: false
        },

        {
          questions: 'Can I offer a discount to selected people?',
          answers: "Yes, you can!  And it's very simple. When creatng your event tickets, in 'advanced settings' you can generate a discount code to share with whoever you like!",
          flag: false
        },

        {
          questions: 'Will I be able to message my attendees?',
          answers: "Yes. If you need to communicate any information or updates you can do so easily through your dashboard.",
          flag: false
        },

        {
          questions: 'Can I run private events?',
          answers: "Absolutely! When you create your event just select 'private' and your event will be hidden from the homepage and search function. You will still have your unique event URL to share it with only the people you want!",
          flag: false
        },

        {
          questions: 'What if I have a recurring event?',
          answers: "Cry... with happiness! Because with one-click you can duplicate your event or enable automatic recurrence ;)",
          flag: false
        }
      ],
    }
  },

  methods: {
    toggle: function(index) {
      for (var i = 0; i < this.faq.length; i++) {
        if (this.faq[index] === this.faq[i]) {
          this.faq[index].flag = !this.faq[index].flag;
        } else {
          this.faq[i].flag = false;
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div class="section10" id="example">
  <div class="content-container qa-content-container">
    <h2>Frequently asked questions,
      <br> answered.
    </h2>

    <div class="column">
      <div class="qanda-div w-col" v-for="(faqs, index) in faq" :key="faqs.questions">
        <button class="qa-toggle-button w-button" @click="toggle(index)">

                            {{faqs.questions}}
                        </button>
        <p class="qa-answer" style="none" v-show="faqs.flag">
          {{faqs.answers}}
        </p>
      </div>
    </div>

    <p class="grey qa-moreQ">
      Got more questions? Ask us
      <a href="mailto:contact@ticketpass.co" class="green">here.</a>
    </p>
  </div>
</div>

Редактировать 2: Это лучший способ сделать это.Я использую indexToShow, эта переменная будет иметь индекс faq, который будет показан.Итак, вы должны проверить, соответствуют ли они v-show="index===indexToShow".Если indexToShow равно -1, никакого ответа не будет.

var example1 = new Vue({
  el: '#example',
  data() {
    return {
      indexToShow: -1,
      faq: [{
          questions: 'Seriously, free?',
          answers: "Yes; as an Organiser you don't pay any setup, monthly or annual fees. With Ticketpass you'll recieve 100% of your ticket sales. We organise events too and know how much time and effort you put into them. You shouldn't be paying fees after all that!",
          flag: false
        },

        {
          questions: 'How do tickets work?',
          answers: "When someone registers for your event or purchases a ticket, we'll send them an email with your event details, a booking reference, and a unique QR code. You will be able to check them in online at the event entrance, or if you are old school, you can download and print a beautiful sheet with your attendees' name and the ticket type they bought. Simple!",
          flag: false
        },

        {
          questions: 'How do I collect my money?',
          answers: "As soon as your event ends, we'll process your payment and arrange for it to be transferred to your account. We understand that in some cases you may need to access your sales revenue before the event in order to cover costs, in which case you can apply for early payment by verifying your identity. Note that depending on your bank it can take a few working days for payments to show in your account.",
          flag: false
        },

        {
          questions: "If it's free, how can you afford coffee?",
          answers: "Ticketpass is completely free for organisers, our costs are covered on card payments when attendees purchase tickets.",
          flag: false
        },

        {
          questions: 'Do I need to pay any processing fees?',
          answers: "Nope, we'll take care of them. - Happy days! :)",
          flag: false
        },

        {
          questions: 'Can I see an attendees list for my event?',
          answers: "Yes - you can view and download an attendee list from your event dashboard, where you can also track registrations and keep an eye on ticket sales 24/7.",
          flag: false
        },

        {
          questions: 'Can I offer a discount to selected people?',
          answers: "Yes, you can!  And it's very simple. When creatng your event tickets, in 'advanced settings' you can generate a discount code to share with whoever you like!",
          flag: false
        },

        {
          questions: 'Will I be able to message my attendees?',
          answers: "Yes. If you need to communicate any information or updates you can do so easily through your dashboard.",
          flag: false
        },

        {
          questions: 'Can I run private events?',
          answers: "Absolutely! When you create your event just select 'private' and your event will be hidden from the homepage and search function. You will still have your unique event URL to share it with only the people you want!",
          flag: false
        },

        {
          questions: 'What if I have a recurring event?',
          answers: "Cry... with happiness! Because with one-click you can duplicate your event or enable automatic recurrence ;)",
          flag: false
        }
      ],
    }
  },

  methods: {
    toggle: function(index) {
	    this.indexToShow = (this.indexToShow === index)? -1 : index;
    }
  }


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div class="section10" id="example">
  <div class="content-container qa-content-container">
    <h2>Frequently asked questions,
      <br> answered.
    </h2>

    <div class="column">
      <div class="qanda-div w-col" v-for="(faqs, index) in faq" :key="faqs.questions">
        <button class="qa-toggle-button w-button" @click="toggle(index)">

                            {{faqs.questions}}
                        </button>
        <p class="qa-answer" style="none" v-show="index===indexToShow">
          {{faqs.answers}}
        </p>
      </div>
    </div>

    <p class="grey qa-moreQ">
      Got more questions? Ask us
      <a href="mailto:contact@ticketpass.co" class="green">here.</a>
    </p>
  </div>
</div>
...