Vue.js v-show in a list

僤鯓⒐⒋嵵緔 提交于 2019-11-29 07:29:47

There's a few ways to approach this depending on your needs.

Multiple Open

You can make each post it's own component, that way you can have show be tied to each individual post instead of all of them.

Vue.component('post', {
  template: '#post-template',
  props: {
    post: Object,
  },
  data() {
    return {
      show: false,
    }
  },
  methods: {
    toggleShow() {
      this.show = !this.show
    },
  },
})

Then you can have use it like this:

<post v-for="post in posts" :post="post"></post>

One Open

If you just want one open you can pass an id as a prop and show it based on that.

Vue.component('post', {
  template: '#post-template',
  props: {
    post: Object,
    selectedId: Number,
  },
  computed: {
    show() {
      return this.post.id === this.selectedId
    },
  },
})

Then you can do like

<post :selected-id="selectedId" :post="post" @click="selectedId = post.id"></post>

I cheated in a different way. Just added a show property to each post and toggled that.

new Vue({
  el: 'body',
  data: {
    list: []
  },
  ready: function() {
    this.fetchPostList()
  },
  methods: {
    fetchPostList: function() {
      setTimeout(function() {
        this.list.push({
          title: 'First Post',
          body: 'This is the first Post',
          userId: 'Joe',
          show: false
        });
        this.list.push({
          title: 'Second Post',
          body: 'This is the second Post',
          userId: 'Joe',
          show: false
        });
        this.list.push({
          title: 'Third Post',
          body: 'This is the third Post',
          userId: 'Joe',
          show: false
        });
      }.bind(this), 2000);
    },
    changeShow: function(idx) {
      this.list[idx].show = !this.list[idx].show;
    }
  }
});
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div class="container">
  <h1>My Posts</h1>
  <ul class="list-group">
    <li class="list-group-item" v-for="post in list">
      <div @click="changeShow($index)">
        <h4>{{ post.title }}</h4>
        <p v-show="post.show">{{ post.body }}</p>
        <span v-show="post.show" class="label label-primary">ID: {{ post.userId }}</span>
      </div>
    </li>
  </ul>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!