0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

computedで動的なプロパティを使って表現する ❏Vue.js❏

Posted at

3より大きいか小さいかを判断します。
その際、computedという新たなものを使います。

Screenshot from Gyazo

開発環境はJSFiddle
https://qiita.com/ITmanbow/items/9ae48d37aa5b847f1b3b

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

【解説】
{{ lessThanThree }}と二重中括弧の中にプロパティを入れます。
JS側でcomputedを記述し、lessThanThreereturnなどメソッドのようにその後を書きます。

メソッドとの違いは、
computed: this.counterの値が変わった時にだけ反応する。
methods: ページの描画が少しでも変わった時に反応する。

counterの値のみに注目したいのでcomputedを使います。


ではまた!
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?