V-if指令未在变量更改时动态更新



我正试图在我的程序中创建一个按钮,该按钮可以切换许多其他内容,并在单击后自动删除。相关HTML如下:

<div id="app">
<button @click="reveal" v-if="!showlists">Start</button>
<ul v-if="showlists">
<list v-for="name in chosenNames" v-bind:name="name"></list>
</ul>
</div>

在这种情况下,无序列表应该显示一次变量"0";showlists";是真的并且按钮应该被移除一次";showlists";是真的。我的Vue应用程序如下:

let app = new Vue({
el: "#app",
data: {
showlists: false,
chosenNames: [
{ text: "name1" },
{ text: "name2" },
{ text: "name3" },
]
},
methods: {
reveal: function() {
showlists = true;
}
}
})

基于此;showlists";变量开始时为false,程序按预期工作,按钮显示,列表隐藏。单击按钮后,函数将运行,showlists将设置为true(我在故障排除工作中确认了这一点(。然而,一旦发生这种情况,DOM就不会动态更新,而是保持最初的状态。

很抱歉,如果这是一些非常基本的东西,我对Vue很陌生,仍在努力学习:(

任何帮助都将不胜感激。

您必须使用;这个";关键字在您的";狂欢;方法之前的类似CCD_ 1的CCD_;Vue";例子

例如,你可以写如下

<div id="app">
<button @click="reveal" v-if="!showlists">Start</button>
<ul v-if="showlists">
<list v-for="(name, index) in chosenNames" :name="name" :key="'list-'+index"></list>
</ul>
</div>

对于新的";Vue";实例

let app = new Vue({
el: "#app",
data: {
showlists: false,
chosenNames: [
{ text: "name1" },
{ text: "name2" },
{ text: "name3" },
]
},
methods: {
reveal: function() {
this.showlists = true;
}
}
})

我希望这能解决问题:(

您的代码有4个错误:

  1. v-bind是set元素的属性,而不是innerHTML
  2. showlists需要对此进行更改。showlists
  3. showlists = true;总是设置为true
  4. 列表不是有效的html标记,您需要li下面是正确的代码:
<div id="app">
<button @click="reveal" v-if="!showlists">Start</button>
<ul v-if="showlists">
<li v-for="name in chosenNames" v-html="name"></li>
</ul>
</div>
<script>
let app = new Vue({
el: "#app",
data: {
showlists: false,
chosenNames: [
{ text: "name1" },
{ text: "name2" },
{ text: "name3" },
]
},
methods: {
reveal: function() {
this.showlists = !this.showlists;
}
}
})
</script>

最新更新