[英]Vue template isn't rendering in for loop
因此,在按照初学者 Vue 教程设置 Todo 应用程序后,我决定尝试调整其中的某些部分以适应我正在尝试制作的网站。 我坚持的是,尽管一切都说我的 for 循环应该工作,但它没有。
该项目本身是使用 vue-cli 创建的,并且大部分代码都是从教程中复制粘贴的。 (使用自己的for循环可以正常工作)
似乎数据可能没有传递到模板上?
我努力了:
(设置新的 vue-cli 项目后:)
应用程序.vue:
<template>
<div id="app">
<create-section v-on:create-section="addSection" />
<section v-for="section in sections" v-bind:key="section.title" :info="section"></section>
</div>
</template>
<script>
import CreateSection from "./components/CreateSection";
import Section from "./components/Section";
export default {
name: "App",
components: {
CreateSection,
Section
},
data() {
return {
sections: []
};
},
methods: {
addSection(section) {
this.sections.push({
title: section.title,
description: section.description
});
console.log(
"Added to sections! : " + section.title + " | " + section.description
);
console.log("Sections length: " + this.sections.length);
}
}
};
</script>
节.vue
<template>
<div class="ui centered card">
<div class="content">
<div class="header">{{ info.title }}</div>
<div>{{ info.description }}</div>
</div>
</div>
</template>
<script type = "text/javascript" >
export default {
props: {info: Object},
data() {
return {};
}
};
</script>
预期结果:在网站上显示部分模板(在使用另一个脚本调用的 addSection 创建它之后。为简洁起见不包括在内)
实际结果:什么都没有显示,只添加了一个空标签
我相信问题在于您将其称为Section
。 由于<section>
是标准 HTML 元素,因此您不能将其用作组件名称。
库中内置了一个警告,但它似乎区分大小写,这并不完全有帮助。 尝试将您的components
部分更改为:
components: {
CreateSection,
section: Section
},
然后,您应该会看到警告。
解决方法就是将其称为其他名称。
这在样式指南的第一个条目中提到:
https://v2.vuejs.org/v2/style-guide/#Multi-word-component-names-essential
section是一个现有的 HTML5 元素,您应该为您的 section 组件命名不同的名称。
如果您真的想命名组件 Section,请将其注册为 'v-section'
问题是,当您在<section v-for="section in sections" v-bind:key="section.title" :info="section"></section>
中执行循环时,Array sections
尚未准备好,那里什么都没有。所以当你向这个数组添加新东西时,你需要触发(计算道具)再次将数据发送到section
组件。
除了使用现有 HTML5 命令作为 Vue 组件名称的问题(顺便说一下,您应该将其更改为另一个名称),您还应该查看如何在 Section.vue 中声明道具。 下面的代码显示了正确的方法:
<script type = "text/javascript" >
export default {
props: ['info'],
data() {
return {};
}
};
</script>
props 接受从父组件声明的属性的名称,并且应该是一个字符串。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.