KJR020 KJR020's Blog

Vue3の復習 tutorial-step4-7

Vue.js
Vue.js - The Progressive JavaScript Framework
Vue.js favicon ja.vuejs.org
Vue.js

イベントリスナー v-on

Vue.js
Vue.js - The Progressive JavaScript Framework
Vue.js favicon ja.vuejs.org
Vue.js
  • v-onディレクティブを使って、イベントリスナーを追加できる
  • v-on@で省略できる

フォームバインディング

Vue.js
Vue.js - The Progressive JavaScript Framework
Vue.js favicon ja.vuejs.org
Vue.js
  • v-on,v-modelを使うと双方向のデータバインディングができる
  • いまさら気づいたが、dataは関数を返す必要があるらしい
    • objectでもよいのでは?と思ったが、dataはコンポーネントのインスタンスごとに異なるデータを持つため、関数を返す必要がある
    • objectを返すと、コンポーネントのインスタンスが共有されてしまう
  • 逆に、methodsはobjectを返す必要がある
    • これは、コンポーネントのインスタンスが共有されても問題ないためか
<script>
  export default {
    data: {
      return {
      text: ''
    }},
    }
    methods: {
      onInput(event) {
        this.text = event.target.value
      }
    },
    }
  }
</script>
<template>
  <input :value='text' @input="onInput">
  <p>{{ text }}</p>
</template>

条件付きレンダリング

<script>
export default {
  data() {
    return {
      isVisible: true
    }
  },
  methods: {
    toggle() {
      this.isVisible = !this.isVisible
    }
  }
}
</script>

<template>
  <button @click="onClick">Toggle</button>
  <h1>Vue is awesome!</h1>
  <h1>Oh no 😢</h1>
</template>

リストレンダリング

Vue.js
Vue.js - The Progressive JavaScript Framework
Vue.js favicon ja.vuejs.org
Vue.js
  • v-forディレクティブを使用すると配列を元にリストをレンダリングできる
<ul>
  <li v-for="item in items" :key="item.id">
    {{ todo.text }}
  </li>
</ul>
  • リストを変更するには、2つの方法があるらしい
    • 配列の変更を追加する

      this.items.push(newItem)
    • 配列を新しい配列に置き換える

      this.items = this.items.filter(/* ... */)  
Esc
キーワードを入力して検索