Vue.js v-显示在列表中

Mio*_*vic 5 javascript vue.js vue-resource

我敢肯定,这对你们来说将会非常容易。我正在尝试使帖子的标题始终保持可见的简单列表,并且当您单击列表中的特定帖子时,您将获得帖子的正文。我为此使用了v-show。但是,当我单击特定帖子时,所有帖子的正文都会出现,而不仅仅是我单击的内容。

这是模板:

<template>
<div class="container">
    <h1>My Posts</h1>
    <ul class="list-group">
        <li class="list-group-item" v-for="post in list">
            <div @click="changeShow">
                <h4>{{ post.title }}</h4>
                <p v-show="show">{{ post.body }}</p>
                <span v-show="show" class="label label-primary">ID: {{ post.userId }}</span>
            </div>
        </li>
    </ul>

</div>
Run Code Online (Sandbox Code Playgroud)

逻辑:

<script>

export default{

    data(){
        return{
            msg:'hello vue',
            list: [],
            show: false
        }
    },
    ready(){
        this.fetchPostList();
    },

    methods:{
        fetchPostList: function () {
            var root = 'http://jsonplaceholder.typicode.com';
            this.$http.get(root + '/posts').then(function (response) {
                this.list = response.data;
            })
        },
        changeShow: function () {
            this.show = !this.show;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Bil*_*ell 5

有几种方法可以根据您的需要进行处理。

多次开放

您可以将每个帖子show设为自己的组件,这样就可以将其绑定到每个单独的帖子,而不是全部绑定到每个帖子。

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

然后,您可以像这样使用它:

<post v-for="post in posts" :post="post"></post>
Run Code Online (Sandbox Code Playgroud)

一开

如果您只想打开一个id,则可以传递一个道具,并以此为基础进行展示。

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

那你就可以喜欢

<post :selected-id="selectedId" :post="post" @click="selectedId = post.id"></post>
Run Code Online (Sandbox Code Playgroud)