[英]VueJS: render new component after click
我想在 vue.js 中渲染新组件,就好像它是新页面一样。
我正在尝试使用称为“动态组件”的东西来做到这一点
父级:Post.vue
孩子:Detail.vue
因此,如果单击其中一个帖子,则帖子关闭,详细信息打开。
问题是我必须将点击的帖子的 ID 发送到详细信息。
这是我的一些代码。
Post.vue
<template>
<div>
<div v-if="loading">
loading...
</div>
<div v-else class="container">
<ul>
<li v-for="(post, index) in filteredPosts" v-bind:key="post.no">
<section class="post__main">
<div @click..?? class="main__title">{{post.title}}</div>
</section>
</li>
</ul>
</div>
</div>
</template>
<script>
created() {
axios.get(this.url, {
params: {
page: this.page,
ord: this.ord,
category: []
}
}).then(res => {
this.posts = res.data.list;
this.loading = false;
this.page++;
});
细节.vue
<template>
<div>
{{contents}}
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Datail',
data() {
return {
req_no: null,
contents: {}
}
},
created() {
axios.get(url, {
params: {
req_no: this.req_no
}
}).then(res => {
this.contents = this.res.data
});
}
}
</script>
我觉得我可以用props
和v-if
做到这一点。 有人能帮我吗? 谢谢!
单击帖子后,将帖子 ID 传递给单击处理程序。 在点击处理程序中,路由到 detail.vue,将 post id 作为路由参数。
如下所示:
<li v-for="(post, index) in filteredPosts" v-bind:key="post.no">
<section class="post__main">
<div @click="onPostClick(post.id)" class="main__title">{{post.title}}</div>
</section>
</li>
在您的点击处理程序中:
onPostClick(id: number) {
this.$router.push({
name: 'details',
params: {
id
}
});
}
如果您在应用程序中正确设置了 vue 路由器并有一个有效的详细路线,这将起作用。
您可以在 details 组件中访问 post id,如下所示:
created() {
this.postId = this.$route.params.id;
}
我会看一下<component>
,它接受一个 prop :to
并渲染一个组件,这对于标签之类的东西很有用,您可以在页面上的相同位置渲染不同的组件,而无需重新加载整个页面。 见这里: https ://v2.vuejs.org/v2/guide/components-dynamic-async.html 这对您来说似乎是一个非常好的用例,只需将您需要的道具传递给component
即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.