【问题标题】:在 vue.js 中触发事件时如何更改样式类
【发布时间】:2019-01-12 08:39:48
【问题描述】:

我的组件中有一个简单的项目列表,并且希望在选择项目后更改样式。目前我通过使用 v-bind:class 和一个布尔变量来尝试这个,当事件被触发时该变量将被更改。我调试了它,但它不起作用,列表元素的类始终保持“list-group-item”而不是预期的“list-group-item active”

        <template>


                    <li     class="list-group-item"
                            style="cursor: pointer"
                            v-bind:class="{active: isActive}"
                            @click="serverSelected">
                        <p> Server <span class="badge badge-secondary">{{ server.id }}</span> [status = {{server.status}}]</p>
                    </li>

        </template>

        <script>
            import { eventBus } from '../../main'
            export default{
                props:['server'],
                methods:{
                    serverSelected: function(){
                        this.isActive = !this.isActive;
                        console.log("active value is: " + this.isActive);
                        eventBus.$emit('serverSelected', this.server);
                        console.log('server selected ' + this.server.id);
                    }
                },
                data:{
                    isActive: false
                }
            }
        </script>

        <style>

        </style>

【问题讨论】:

标签: vue.js vuejs2 vue-component


【解决方案1】:

datashould be a function,这样每个实例都可以维护返回数据对象的独立副本

data: function () {
  return {
     isActive: false
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多