为什么我的Vue应用程序没有渲染,尽管挂载的事件已启动



因此,这里有一个奇怪的案例。代码在codepen中工作(甚至在堆栈溢出的代码呈现器中(,但在我的github页面网站上不工作。

没有错误触发,创建和装载的事件的控制台日志也会正常运行,但元素不会在网页上呈现。

(function() {
console.log('test', Vue);
const contentCards = [
{
'anchor': 'hero',
'title': 'Cold Throne Steel',
'body': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
}
];
Vue.component('content-card', {
props: ['anchor', 'title', 'body'],
template: `
<section class="content-card" v-bind:id="anchor">
<h1 class="content-card__title">{{ title }}</h1>
<p class="content-card__body">{{ body }}</p>
</section>`
});
const root = new Vue({
el: "#main-content",
created: function() {
console.log('element has been created')
},
mounted: function() {
console.log('element has been mounted')
},
data: {
cards: contentCards
}
});
console.log('root', root);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
</head>
<body>
<main id="main-content">
<content-card v-for="card in cards" v-bind:key="card.anchor" v-bind:anchor="card.anchor" v-bind:title="card.anchor" v-bind:body="card.body"></content-card>
</main>
</body>
</html>

您可以在此处查看页面:https://coldthronesteel.com/看看Vue应用程序不工作。。。尽管所有控制台日志都建议它应该!

在执行脚本之前,您必须等待元素加载到DOM中。一种方法是将脚本标记放在元素后面:

<main id="main-content">
<content-card v-for="card in cards" v-bind:key="card.anchor" v-bind:anchor="card.anchor" v-bind:title="card.anchor" v-bind:body="card.body"></content-card>
</main>
<script src="scripts/scripts.js"></script>

或者您可以使用DOMContentLoaded事件。


*它在CodePen中工作的原因是它将脚本部分放在</body>标记之前。它确保DOM准备就绪

最新更新