关于我问 here 的问题,我意识到我的问题可能是因为模板是在脚本之前加载的,当它收到变量未定义的错误时,它会停止脚本运行。如果是这种情况,那么可能是因为 use strict
位于我的 node_modules 中,而不是在我的代码中。
我的组件如下所示:
<style lang="sass">
.hero {
color: white;
padding-top: 10em;
}
.image {
background: no-repeat;
background-size: 100% 100%;
height: 600px;
box-shadow:inset 0 0 0 2000px rgba(0,0,50,0.3);
}
</style>
<template>
<div :style="{ backgroundImage: 'url(' + components.carousel.content.image + ')' }" class="image">
<div class="row hero">
<div class="small-8 medium-6 columns">
<h2>Welcome to <strong>{{components.site.name}}</strong>
<br/> {{components.carousel.content.tag_line}}</h2>
<br>
<p>
{{components.carousel.content.perks_1}} |
{{components.carousel.content.perks_2}} |
{{components.carousel.content.perks_3}}
</p>
</div>
</div>
</div>
</template>
<script>
import homepageMixin from '../mixin';
export default {
mixins: [homepageMixin],
data: function () {
return {
components: ''
}
}
}
</script>
当我加载时出现此错误:
[Vue warn]: Error when rendering component carousel: ...
vue.js?3de6:2229 Uncaught TypeError: Cannot read property 'content' of undefined
我已经这样使用它很长一段时间了,因为它在模板中加载数据并替换它,但是在我尝试安装 babel 后,它现在以某种方式强制使用严格。当我检查前后编译的 JS 文件之间的差异时,我意识到这一行位于底部,但现在它在我的组件之前在顶部编译。
var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() { return this; })();
解决方案是首先加载脚本,以便在加载模板时数据可用。我怎样才能做到这一点?
最佳答案
如果您调用components.carousel
,这不会成为问题,但您正在尝试获取嵌套未定义的嵌套属性。这与 VueJS 问题无关。
但是,最好将所有可能未定义的内容放在 v-if
相关项下。在您的情况下,在顶部节点元素上使用 v-if='components.carousel'
。那么它就会很好地工作。
关于javascript - 如何在 <template> 之前加载 Vuejs 单文件组件的 <script> 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41931173/