首页 > 解决方案 > Vue onclick 显示特定项目

问题描述

我有一个关于 Vue 的问题。

我想为特定项目添加一个类:

<p v-on:click="display = !display">Rediger joke</p>

之前显示为假,将其更改为真。

它有效。但我的问题是,这个 onclick 在一个 v-for 循环中,我只想将“显示”放在一个“更新站点”上,而不是全部。我可以这样做还是必须尝试不同的设置?

非常感谢

标签: vuejs2

解决方案


我有这个想法可能会对你有所帮助。post这个想法是您使用例如属性扩展对象,visible当您click event触发时,您更改此属性并添加.display类。请检查这个jsfiddle

模板

 <div id="app">
   <article v-for="post in filteredPosts" :key="post.id">
     {{post.name}}
     <button @click="display(post)">show</button>
     <div class="post-content" :class="{display: post.visible}">this is the part I want to display onclick</div>
     <hr />
   </article>
 </div>

css

.post-content {
  display: none;
}

.post-content.display {
  display: block;
}

代码

new Vue({
  el: '#app',
  data() {
    return {
      posts: []
    };
  },
  created() {
    //when you load posts. add visible property.
    setTimeout(() => {
      //posts from server
      var postsFromServer = [{
          id: 1,
          name: 'Post One'
        },
        {
          id: 2,
          name: 'Post Two'
        }
      ];

      //add visible proprty.
      this.posts = postsFromServer.map(post => {
        return {
          ...post,
          visible: false
        };
      });
    }, 1000);
  },
  computed: {
    filteredPosts() {
      //do your filters
      return this.posts;
    }
  },
  methods: {
    display(post) {
      this.$set(post, 'visible', !post.visible);
    }
  }
});

推荐阅读