LoginSignup
15
12

More than 5 years have passed since last update.

Vueテンプレート構文:条件で属性を付けたり外したり【備忘録】

Last updated at Posted at 2019-02-15

属性値のバインディングはわかるけど、
属性自体の切替はどうやるんだと迷ったので備忘録。

やりたいこと

  • blankフラグがfalseのときはtarget属性無し
  • blankフラグがtrueのときはtarget属性有り
template.vue
<template lang="pug">
.component
  template(v-for="item in linkList")
    // blankフラグがfalseのときはtarget属性なし
    a(:href="item.href")
      |{{item.text}}
    // blankフラグがtrueのときはtarget="_blank"
    a(:href="item.href" target="_blank")
      |{{item.text}}
</template>
<script>
export default {
  data(){
    return {
      linkList: [
       {
         text: "同窓リンク",
         href: "hoge.hoge",
         blank: false
       },
       {
         text: "別窓リンク",
         href: "fuga.fuga",
         blank: true
       },
      ]
    }
  }
}
</script>

やり方

三項演算子を使って不一致時にfalsenullを渡してあげると属性ごと消えてくれた

属性が一個だけの時

OK.vue
<template lang="pug">
.component
  template(v-for="item in linkList")
    a(:href="item.href" :target="item.blank? '_blank':false")
      |{{item.text}}
</template>

OK.html
<a href="hoge.hoge">同窓リンク</a>
<a href="fuga.fuga" target="_blank">別窓リンク</a>

属性が複数の時

v-bindの引数を省略すると複数の属性をオブジェクトで渡せるので、
rel="noopener noreferrer"もつけたりとか、複数の属性をつけるならこっちが楽

OK.vue
<template lang="pug">
.component
  template(v-for="item in linkList")
    a(:href="item.href" v-bind="item.blank? {target:'_blank',rel:'noopener noreferrer'}:false")
      |{{item.text}}
</template>

OK.html
<a href="hoge.hoge">同窓リンク</a>
<a href="fuga.fuga" target="_blank" rel="noopener noreferrer">別窓リンク</a>

NGな例

最初なにも考えずにクラスバインディングのノリでオブジェクト構文で書いてみたらダメだった
オブジェクトを渡せるのはv-bind(引数省略時)と、v-bind:classv-bind:styleのみ
https://jp.vuejs.org/v2/api/#v-bind

NG.vue
<template lang="pug">
.component
  template(v-for="item in linkList")
    a(:href="item.href" :target="{_blank:item.blank}")
      |{{item.text}}
</template>

NG.html
<a href="hoge.hoge" target="[object Object]">同窓リンク</a>
<a href="fuga.fuga" target="[object Object]">別窓リンク</a>
15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12