我正在使用 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/[email protected] /cdn-cgi/l/email-protection/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>
来自Vue.js - 深度反应性文档 https://v2.vuejs.org/v2/guide/reactivity.html#Async-Update-Queue:
例如,当您设置 vm.someData = 'new value' 时,组件
不会立即重新渲染。它将在下一个“tick”中更新,
当队列被刷新时。
随着数据在创建的生命周期钩子中发生变化,我们需要使用$nextTick
有关更多信息,请参阅上面的页面。
var step1 = Vue.component('step1', {
template: '#step1',
data: function() {
return {
accounts: [],
isloaded: false
}
},
created: function() {
console.log("created");
var self = this;
setTimeout(function() {
console.log("times over");
self.$nextTick(function() {
self.isloaded = true;
self.accounts = [{
id: 1234,
name: "germany"
}];
})
}, 2000);
}
})
new Vue({
el: '#main'
});
<script src="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/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>
但是,如果将加载数据的代码放在方法中,并从created
钩。它的工作原理无需$nextTick
.
methods: {
loadData: function() {
var self = this;
setTimeout(function() {
console.log("times over");
self.isloaded = true;
self.accounts = [{
id: 1234,
name: "germany"
}];
}, 2000);
}
},
created: function() {
console.log("created");
this.loadData();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)