简体   繁体   English

v-for循环中的Vue3切换元素

[英]Vue3 toggle element in v-for loop

I am looping through an array on v-for loop in vue 3. Is there a way to toggle the v-show of a paragraph by clicking on the Heading element.我在 vue 3 的 v-for 循环中循环一个数组。有没有办法通过单击 Heading 元素来切换段落的 v-show。 Below is my code:下面是我的代码:

<div class="defs">
<ul v-for="(d, index) in definitions"
              :key="'d' + index">
   <li>
  <div class="project" >
    <div @click="showDetails" class="actions">
      <h3>{{ d.title }}</h3>
      <div class="icons">
         <span  class="material-icons" ><i class="fas fa-trash-alt"></i></span> 
  <span class="material-icons" ><i class="fas fa-pencil-alt"></i></span> 
      </div>
    </div>
    <div v-if="show" class="details">
      <p>{{d.explanation}}</p>
    </div>
  </div>
  </li>
</ul>
</div>



<script>
import { ref } from "vue";
import { projectDatabase} from '../../firebase/config'

export default {
  props: ['id'],
  setup(props){

  const show = ref(false);

  
  
  const showDetails = () =>{
    show.value = !show.value
  }

      return {
      definitions, props, show, showDetails, 
    }
  }
}
</script>

I know we cant use this in composition API.我知道我们不能在作文 API 中使用它。 so how can we solve the toggle issue?那么我们如何解决切换问题呢?

Try like following snippet, here is the codesandbox with composition API试试下面的代码片段,这里是组成 API的代码框

 const demo = { data() { return { definitions: [ { title: "aaa", explanation: "aaa" }, { title: "bbb", explanation: "bbb" }, { title: "ccc", explanation: "ccc" }, ], show: null } }, methods: { showDetails(idx) { this.show === idx? (this.show = null): (this.show = idx); } }, // same code with coposition API /*import { ref } from "vue"; import { projectDatabase} from '../../firebase/config' setup() { const show = ref(null); const definitions = ref([ { title: "aaa", explanation: "aaa" }, { title: "bbb", explanation: "bbb" }, { title: "ccc", explanation: "ccc" }, ]); const showDetails = (idx) => { show.value === idx? (show.value = null): (show.value = idx); }; return { definitions, show, showDetails } },*/ }; Vue.createApp(demo).mount("#demo");
 <script src="https://unpkg.com/vue@next"></script> <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" /> <div id="demo"> <div class="defs"> <ul> <li v-for="(d, index) in definitions":key="index"> <div class="project"> <div @click="showDetails(index)" class="actions"> <h3>{{ d.title }}</h3> <div class="icons"> <span class="material-icons" ><i class="fas fa-trash-alt"></i ></span> <span class="material-icons" ><i class="fas fa-pencil-alt"></i ></span> </div> </div> <div v-if="show === index" class="details"> <p>{{ d.explanation }}</p> </div> </div> </li> </ul> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM