我正在玩 vue.js 并且在正确使用 v-if 方面遇到了一些困难。
我正在尝试在模板中呈现条件模板。在创建的方法中,变量 isloaded
设置为 true,这将导致模板重新呈现并让“加载数据”消息消失。
然而,日志表明,2s 的延迟有效,因此达到了回调,但看起来我没有正确更新数据变量。
我已经尝试了几件事,现在我将“true/false”更改为字符串,以便更接近官方主页上给出的示例,但仍然没有成功。我希望你能帮助我,因此非常感谢。
请在下面找到有趣的代码片段:
var step1 = Vue.component('step1', {
template: '#step1',
data: function() {
return {
accounts: [],
isloaded: 'false'
}
},
created: function() {
console.log("created");
setTimeout(function() {
console.log("times over");
this.isloaded = 'true';
this.accounts = [{
id: 1234,
name: "germany"
}];
}, 2000);
},
methods: {
loaded: function() {
console.log(this.isloaded === 'true');
return this.isloaded === 'true';
}
}
})
new Vue({
el: '#main'
});
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<template id="step1">
<div class="step1">
<h1>Welcome please choose your account:</h1>
<template v-if="isloaded === 'false'">
<p>Loading Data</p>
</template>
<template v-else>
<select>
<template v-for="account in accounts">
<option :value="account.id">{{ account.name }}</option>
</template>
</select>
</template>
</div>
</template>
<div id="main">
<step1></step1>
</div>
原文由 Manuel Jain 发布,翻译遵循 CC BY-SA 4.0 许可协议
来自 Vue.js - 反应性深度文档:
随着数据在创建的生命周期挂钩中发生变化,我们需要使用
$nextTick
更多信息可以在上面的页面中找到。但是,如果您将加载数据的代码放在一个方法中,并从
created
挂钩调用该方法。它在没有$nextTick
的情况下工作。