【发布时间】:2017-05-30 06:17:29
【问题描述】:
我正在通过编写一个小脚本来学习 Vue.js,结果遇到了一种 catch 22 的情况。
处理 Vue.js 部分的 JS 脚本 (explorer.js):
var vm = new Vue({
el: "#root",
data: {
posts: {},
tags: {}
}
})
qwest.get('/posts.json')
.then(function (xhr, response) {
vm.posts = response;
});
qwest.get('/tags.json')
.then(function (xhr, response) {
vm.tags = response;
});
案例一:提前加载explorer.js:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qwest/4.4.6/qwest.min.js"></script>
<link rel="stylesheet" href="/static/css/explorer.css">
<script src="/static/js/explorer.js"></script>
<div id="root">
<button v-for="(content, title) in posts" class="l1 btn">
{{ title }}
<button v-for="tag in content.tags" class="l2 btn">
{{ tag }}
<button v-for="t in tags[tag]" class="l3 btn">
{{ t }}
</button>
</button>
</button>
</div>
我从 Vue 收到 Cannot find element: #root 错误。
这是可以理解的:当explorer.js 运行时,<div id="root"> 还不知道。
案例2:加载explorer.js延迟:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qwest/4.4.6/qwest.min.js"></script>
<link rel="stylesheet" href="/static/css/explorer.css">
<div id="root">
<button v-for="(content, title) in posts" class="l1 btn">
{{ title }}
<button v-for="tag in content.tags" class="l2 btn">
{{ tag }}
<button v-for="t in tags[tag]" class="l3 btn">
{{ t }}
</button>
</button>
</button>
</div>
<script src="/static/js/explorer.js"></script>
我收到 Property or method "data" is not defined on the instance but referenced during render. 错误(以及其他相同样式的错误)。
这也是可以理解的:v-for 函数尝试访问尚未定义的数据。
我应该如何(或者更确切地说 - 在哪里)加载 explorer.js?
【问题讨论】:
标签: javascript vue.js