VueJS切换支持布尔值与计算属性相比

时间:2017-09-17 21:33:20

标签: vue.js vuejs2 vue-component

我有一个名为navbar-base的组件的代码如下:

<template>
  <nav class="navbar" role="navigation" aria-label="main navigation">
      <div class="navbar-brand">
        <slot name="brand"></slot>
        <button class="button navbar-burger" v-if="burger" >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>

      <div class="navbar-menu">
        <div class="navbar-start">
          <slot name="menu-left"></slot>
        </div>

        <div class="navbar-end">
          <slot name="menu-right"></slot>
        </div>
      </div>
  </nav>
</template>

<script>
export default {
  props: {
    burger: {
      type: Boolean,
      default: false
    }
  },

  computed: {
    hasBurger () {
      this.burger = true
      return this.burger
    }
  }
}
</script>

我想要做的是能够按如下方式打开或关闭navbar-burger

汉堡可见(切换开启)

<navbar-base class="is-info" hasBurger>

 <a href="#" class="navbar-item" slot="brand">Brand name</a>
 <a href="#" class="navbar-item" slot="menu-left">Courses</a>
 <a href="#" class="navbar-item" slot="menu-right">Videos</a>
 <a href="#" class="navbar-item" slot="menu-right">Login</a>
 <a href="#" class="navbar-item" slot="menu-right">Signup</a>

</navbar-base>

汉堡不可见(切换关闭)

<navbar-base class="is-info">

 <a href="#" class="navbar-item" slot="brand">Brand name</a>
 <a href="#" class="navbar-item" slot="menu-left">Courses</a>
 <a href="#" class="navbar-item" slot="menu-right">Videos</a>
 <a href="#" class="navbar-item" slot="menu-right">Login</a>
 <a href="#" class="navbar-item" slot="menu-right">Signup</a>

</navbar-base>

换句话说,如果我将hasBurger添加到<navbar-base>标记,则会包含汉堡代码。否则它不会。

问题是我的代码无效 - 而且我不确定如何让它运行。

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:0)

我得到了它的工作。关键是实际上根本不使用计算属性。这是工作代码(如果有人发现它有用):

<template>
  <nav class="navbar" role="navigation" aria-label="main navigation">
      <div class="navbar-brand">
        <slot name="brand"></slot>
        <button class="button navbar-burger" v-if="hasBurger" >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>

      <div class="navbar-menu">
        <div class="navbar-start">
          <slot name="menu-left"></slot>
        </div>

        <div class="navbar-end">
          <slot name="menu-right"></slot>
        </div>
      </div>
  </nav>
</template>

<script>
export default {
  props: {
    hasBurger: {
      type: Boolean,
      default: false
    }
  }
}
</script>