Vuejs open/toggle single item

2019-02-19 06:38发布

问题:

I work with single file components and have a list in one of them. This list should work like a accordion, but as far as I can find in the Vuejs docs, it's not that easy to make each item open separately very easily. The data (questions and answers) is retrieved from an ajax call. I use jQuery for that, but would like to know how I can make the accordion work Vuejs-style. Any help would be appreciated!

Here's the code:

export default {
  name: 'faq-component',
  props: ['faqid', 'faqserviceurl', 'ctx'],
  data: function () {
    return {
    	showFaq: "",
    	totalFaqs: this.data,
    	isOpen: true
     }
  },
  watch: {	  
	 'showFaq': function(val, faqid, faqserviceurl) {
		 var self = this;
		 $.ajax ({
             url: this.faqserviceurl,
             type: 'GET',
             data: {id: this.faqid, q: val, scope:1},
             success: function (data) { 
                self.totalFaqs = data; 
             },
             error: function () {
             	$("#answer").html('Sorry');
             }			 
		 });
	  }
  },
  methods: {
	  'toggle': function() {
		  this.isOpen = !this.isOpen
		  
	  }
  }
  
}
<template>
	<div class="card faq-block">		
		<div class="card-block">		
			<form>
				<div class="form-group">
					<input class="form-control" type="text" placeholder="Your question" id="faq" v-model="showFaq">
				</div>
			</form>		
			
			<div id="answer"></div>		
			<ul class="faq">
				<li v-for="faq in totalFaqs">
					<p class="question" v-html="faq.vraag" v-bind:class={open:isOpen} @click="isOpen = !isOpen"></p>
					<p class="answer" v-html="faq.antwoord"></p>
				</li>
			</ul>					
		</div>
	</div>
</template>

回答1:

Add an isOpen property to each object in totalFaqs and use that instead of your single isOpen property in data.

<p class="question" v-html="faq.vraag" v-bind:class={open: faq.isOpen} @click="faq.isOpen = !faq.isOpen"></p>

If you can't change the model from the server side, then add it client side.

success: function (data) {
  data.forEach(d => self.$set(d, 'isOpen', false)) 
  self.totalFaqs = data 
}