我试图复制vue教程示例(在这里找到:https://v3.vuejs.org/guide/component-basics.html#passing-data-to-child-components-with-props),但没有成功。下面是我的代码。我有一个叫做TA的视图。Vue,我想要导入组件并渲染。你知道我做错了什么吗?
助教。Vue(视图):
<template id="front">
<b-container style="margin-top: 9rem;">
<b-row>
<div id="blog-posts-events-demo" class="demo">
<div>
<blog_post
v-for="post in posts"
:key="post.id"
:title="post.title"
></blog_post>
</div>
</div>
</b-row>
</b-container>
</template>
<script>
import blog_post from '../components/blog_post' // import the Header component
export default {
name: 'talent-acquisition',
components: {
blog_post
}
}
</script>
blog_post组件:
Vue.component('blog_post', {
el: '#front',
data() {
return {
posts: [
{ id: 1, title: 'My journey with Vue'},
{ id: 2, title: 'Blogging with Vue'},
{ id: 3, title: 'Why Vue is so fun'}
]
}
},
props: ['title'],
template: `
<div class="blog_post">
<h4>{{ title }}</h4>
</div>
`
})
app.mount('#blog-posts-events-demo')
编辑:在遵循Amaarrockz的建议后,我有以下错误:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Failed to mount component: template or render function not defined.
found in
---> <BlogPost> at src/components/blog_post.vue
<TalentAcquisition>
<App> at src/App.vue
<Root>
事情是你有数组'posts'定义在你的子组件('blog_post'),你正试图从父迭代。更好的实现是在父组件中定义数组。请看下面的修改
TA.vue
<template id="front">
<b-container style="margin-top: 9rem;">
<b-row>
<div id="blog-posts-events-demo" class="demo">
<div>
<blog_post
v-for="post in posts"
:key="post.id"
:title="post.title"
></blog_post>
</div>
</div>
</b-row>
</b-container>
</template>
<script>
import blog_post from '../components/blog_post' // import the Header component
export default {
name: 'talent-acquisition',
components: {
blog_post
},
data() {
return {
posts: [
{ id: 1, title: 'My journey with Vue'},
{ id: 2, title: 'Blogging with Vue'},
{ id: 3, title: 'Why Vue is so fun'}
]
}
},
}
</script>
blog_post组件:
Vue.component('blog_post', {
el: '#front',
props: ['title'],
template: `
<div class="blog_post">
<h4>{{ title }}</h4>
</div>
`
})
app.mount('#blog-posts-events-demo')