LoginSignup
0
0

More than 1 year has passed since last update.

computedプロパティ

Last updated at Posted at 2021-05-05
<body>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
  <div id="app">
    <p>{{ counter }}</p>
    <button @click="counter += 1">+1</button>
    <p>{{ counter > 3 ? '3以上' : '3以下'}}</p>
</div>
<script>
  new Vue({
    el: '#app',
    data: {
     counter: 0
    }
  })
</script>
</body>

三項演算子・・・ifを用いない条件分岐の書き方
if文でブロックを分けたくない場合に、コンパクトに条件分岐を書くことができるとても便利な構文です。

条件式 ? 条件がtrueの場合の処理 : 条件がfalseの場合の処理
(重要)

Vueインスタンス内のデータには初期値となるデータしかかけない。動的なデータは扱えません。

そこで

computedプロパティ

<body>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
  <div id="app">
    <p>{{ counter }}</p>
    <button @click="counter += 1">+1</button>
    <p>{{ lessThanThree }}</p>
</div>
<script>
  new Vue({
    el: '#app',
    data: {
     counter: 0
    },
    computed: {
      lessThanThree: function() {
        return this.counter > 3 ? '3以上' : '3以下'
      }
    }
  })
</script>
</body>

同じように表現できました。

20210505-190058.png

0
0
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
0
0