3 javascript templates loops vue.js vuejs2
所以这是我使用vue框架的第一步,我正在尝试制作一个简单的帖子列表组件,在其中使用v-for指令,但是却收到以下消息:
“ eslint-eslint:模板根禁止使用v-for指令”
那我应该如何循环渲染每个帖子?
我将从laravel后端将allBehaviourPosts作为组件传递给组件,如下所示:
<related-post-list :relatedBehaviourPost= {{ $relatedBehaviourPosts }}></>
Run Code Online (Sandbox Code Playgroud)
<template>
<div class="sidebar_related_content_container" v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id" style="">
<a class="sidebar_related_content_image" href="/conducta-canina/{{ relatedBehaviour.slug }}" style="background-image:url('{{ behaviour.image }}');">
<div class="black_gradient" style=""></div>
</a>
<div class="sidebar_related_content_text_container" style="">
<span class="sidebar_related_content_text_title" style="">{{ behaviour.postcategory.name }}</span>
<span class="sidebar_related_content_text_description" style="">{{ behaviour.title }}</span>
</div>
</div>
</template>
<!--SCRIPTS-->
<script>
export default {
props: ['relatedBehaviourPosts'],
data: function () {
return {
//data
}
},
mounted() {
console.log('Footer mounted.')
}
}
</script>
<!--STYLES-->
<style scoped>
</style>
Run Code Online (Sandbox Code Playgroud)
每个组件只能包含一个根元素,这将阻止在根元素上进行条件渲染或列表渲染。您将必须将列表包装在另一个元素(例如a div
)中,并使其成为根:
<template>
<div> <!-- single root element here -->
<div v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id">
<!-- ... -->
</div>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
另请注意,Vue 2在属性绑定中不支持字符串插值,因此必须将其替换为以下语法的数据绑定:
:ATTRIBUTE_NAME="VALUE"
Run Code Online (Sandbox Code Playgroud)
特别是,替换为:
<a href="/conducta-canina/{{ behaviour.slug }}"
style="background-image:url('{{ behaviour.image }}');"></a> <!-- DON'T DO THIS -->
Run Code Online (Sandbox Code Playgroud)
与此(使用ES2015模板文字):
<a :href="`/conducta-canina/${behaviour.slug}`"
:style="`background-image:url('${behaviour.image}');`"></a>
Run Code Online (Sandbox Code Playgroud)
或与此(使用字符串连接):
<a :href="'/conducta-canina/' + behaviour.slug"
:style="'background-image:url(\'' + behaviour.image + '\');'"></a>
Run Code Online (Sandbox Code Playgroud)