vue绑定类不会更新

时间:2019-08-12 18:14:16

标签: javascript css vue.js

<div id="nav">
    <div v-bind:class="['staticClass', { 'show' : visible }]"></div>
</div>

脚本:

var nav = new Vue({
    el: '#nav',
    data: {
        visible: false
    }
});

document.getElementById('hamburger', addEventListener('click', function(){
    nav.visible = !nav.visible;
}

最初有效。仅在visible为true时才添加“ show”类。在单击“汉堡包”时nav.visible会正确更改,但类绑定不会更新。创建页面后,无论nav.visible值如何,都不会添加或删除“ Show”类。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

您应该这样做:

Vue.config.devtools = false
Vue.config.productionTip = false

const nav = new Vue({
    el: '#nav',
    data: {
      visible: false
    },
    methods: {
      toggleClass() {
        this.visible = !this.visible  
      }
    }
});
.staticClass {
  display: none
}

.show {
  display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="nav">
    <button @click="toggleClass">hamburger</button>
    <div 
      v-bind:class="['staticClass', { 'show' : visible }]">
      foo
    </div>
</div>