Vue.js在列表中进行v-show [英] Vue.js v-show in a list
问题描述
我相信这对你们来说非常容易。我正在尝试制作一个简单的帖子列表,其中帖子标题始终可见,当您点击列表中的特定帖子时,您将获得帖子的正文。我用v-show。但是,当我点击特定帖子时,会显示所有帖子的正文,而不仅仅是我点击的帖子。
I'm sure this one's gonna be extremely easy for you guys. I am trying to make a simple list of posts with the post titles always visible, and when you click a specific post in the list, you get the post's body. I used v-show for that. However, when I click a specific post, the bodies of all of the posts appear, instead of just the one that I clicked.
以下是模板:
<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>
逻辑:
<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;
}
}
}
推荐答案
根据您的需要,有几种方法可以解决这个问题。
There's a few ways to approach this depending on your needs.
您可以将每个帖子设为自己的组件,这样您就可以将 show
绑定到每个人而不是所有这些。
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>
一次开启
如果你只是想要一打开你可以传递 id
作为道具并根据它显示。
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
},
},
})
然后你可以这样做
<post :selected-id="selectedId" :post="post" @click="selectedId = post.id"></post>
这篇关于Vue.js在列表中进行v-show的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!