【问题标题】:Problem applying conditional CSS class using Vue.js使用 Vue.js 应用条件 CSS 类的问题
【发布时间】:2018-09-05 08:05:51
【问题描述】:

我有一个显示帐户余额的跨度。您可以单击它来编辑该余额。您可以在下面看到我在更改编辑变量时将hidden 类应用于元素。

<span @click="updateEditAccount(true, false)" v-bind:class="{ hidden: account.editing == true }">Balance ${{ account.balance }}</span>
<input v-bind:class="{ hidden: account.editing == false }" type="number" step="0.01" v-model="account.balance" >

这是改变该值的方法

updateEditAccount(editValue, updateLedger) {
    this.account.editing = editValue
    alert(this.account.editing)
    if(updateLedger) {

    }
},

当我将初始值设置为 true 或 false 时,它​​会显示正确的值。调用该方法时,我可以看到该值已正确更改。

隐藏类就是display:none;

所以值确实改变了,但可见元素没有改变。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    这是常见的reactive problem。你可以使用Vue.set

    updateEditAccount(editValue, updateLedger) {
        this.$set(this.account, 'editing', editValue)
        if(updateLedger) {
    
        }
    }
    

    更新:

    或者你可以使用深拷贝:

    updateEditAccount(editValue, updateLedger) {
        this.account.editing = editValue
        this.account = JSON.parse(JSON.stringify(this.account))
        if(updateLedger) {
    
        }
    }
    

    ES6

    updateEditAccount(editValue, updateLedger) {
        this.account = {...this.account, editing: editValue}
        if(updateLedger) {
    
        }
    }
    

    【讨论】:

    • 我做了这个改变,但有同样的问题。两种方式都会改变价值。如果我在更新后检查该值,则模型具有正确的值,但显示的元素不会改变。
    • 我更新了我的答案。可以试试深拷贝解决方案吗?
    • 有一种情况this.account.editing更新了,但是Vue组件没有再次渲染。
    • 据我了解,当您更新 this.account.editing 时,this.account 仍然指向旧对象,Vue 无法识别数据更改。它不会重新渲染 HTML 元素。仅当this.account 对象更改时才会重新渲染。
    • 您可能想尝试this.$forceUpdate(),但我不确定这是否有效。我通常使用 ES6 语法的深拷贝。
    猜你喜欢
    • 2017-08-21
    • 2017-05-10
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2018-02-06
    • 2011-08-10
    • 2018-04-23
    • 2020-06-20
    相关资源
    最近更新 更多