我正在玩 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>
最佳答案
来自Vue.js - Reactivity in Depth docs :
For example, when you set vm.someData = 'new value', the component will not re-render immediately. It will update in the next “tick”, when the queue is flushed.
随着数据在创建的生命周期钩子(Hook)中发生变化,我们需要使用 $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/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>
但是,如果您将加载数据的代码放在一个方法中,并从 created
Hook 调用该方法。它在没有 $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();
}
关于javascript - Vue.js v-if 不响应变量变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41960271/