首页 > 解决方案 > 真或假的v-bind条件不起作用

问题描述

基本上,我有一个菜单按钮。默认情况下,它是假的。当我单击它时,它被设置为 true。

如果它是真的,我想应用一种marginLeft:250px 的样式,如果它是假的,我想应用marginLeft:0,但我似乎根本无法让我的代码工作。

v-bind 标签应该检查 isOpen 是否为真,如果是,则应用“open”

   <span class="open-slide" @click="openSlide()" v-bind:style="{'open': isOpen}">

const app = new Vue({
    el: '#test',
    data: {
        isOpen: false,
        moreinfo: false,
        open: {
          marginLeft:"250px"  
        },
        locations: [
            {
                name: "Europe",
                desc: "Phasellus non pulvinar elit. Etiam id fringilla eros. Mauris mi odio, fringilla eget tempus eu, vehicula nec neque.",
                img: "img/europe.jpg",

                moreinfo: [
                    {
                        desc: "Euro desc",
                    header: "Welcome to Europe"
                    }
                ]
            },
            {
                name: "America",
                desc: "Curabitur vel lacus ipsum. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris ex ante, scelerisque vitae semper ut",
                img: "https://images.fineartamerica.com/images-medium-large-5/14-american-flag-les-cunliffe.jpg",
               moreinfo: [
                    {desc: "America desc",
                    header: "Welcome to America"}
                ]
            },
            {
                name: "Scotland",
                desc: "Phasellus non pulvinar elit. Etiam id fringilla eros. Mauris mi odio, fringilla eget tempus eu, vehicula nec neque.",
                img: "https://images-na.ssl-images-amazon.com/images/I/41VvuLQ7UhL.jpg",
                moreinfo: [
                    {desc: "Scotland desc",
                    header: "Welcome to Scotland"}
                ]
            },

        ],
        selected: location[1],
    },
        created: function(){
    this.selected = this.locations[0]
  },
    methods:{ 
        moreinfo2(location) {
        this.selected = location;
        },
        openSlide: function() {
            this.isOpen = !this.isOpen;
            if(this.isOpen){
                console.log("True")
            } else {
                console.log("False")
            }
        }
    }
})

标签: htmlcssvue.js

解决方案


问题是您使用Vue 的漂亮对象语法绑定到元素style属性,其 CSS 样式无法识别:

<span class="open-slide" @click="openSlide()" v-bind:style="{'open': isOpen}">

open未被识别为有效的 CSS 规则,所以我假设您想要做的是绑定到class

<span @click="openSlide()" v-bind:class="{open: isOpen, openSlide: isOpen}">

最后,不要忘记在 CSS 文件或内联样式标签中定义 CSS 选择器(使用所有规则):

<style>
   .open {
      /* css styling goes here */
   }
</style>

我希望这有帮助!


推荐阅读