【问题标题】:V-if directive not dynamically updating on variable changeV-if 指令不会在变量更改时动态更新
【发布时间】:2021-08-21 03:59:28
【问题描述】:

我正在尝试在我的程序中创建一个按钮,该按钮可以切换许多其他内容,并在单击后自行删除。相关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>

在此,无序列表应在变量“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 很陌生,仍在努力学习 :)

我们将不胜感激。

【问题讨论】:

  • 应该是this.showlists = true; 而不是showlists = true codesandbox

标签: javascript vue.js


【解决方案1】:

你必须在你的“revel”方法中在showlists之前使用“this”关键字,就像你的“Vue”实例中的this.showlists = true;变量一样。

比如可以这样写

<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;
        }
    }
})

我希望这可以解决问题:)

【讨论】:

    【解决方案2】:

    您的代码有 4 个错误:

    1. v-bind 是设置元素的属性,而不是innerHTML
    2. 演出列表需要更改为 this.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>
    

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 2021-05-25
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2015-05-16
      相关资源
      最近更新 更多