LoginSignup
2
0

More than 3 years have passed since last update.

初めてのVue.js備忘録 vol.01

Posted at

はじめに

今回は、エンジニアになって約半年の私がjavascriptのフレームワークであるVue.jsを使って開発を行ったので、そのVue.jsの基本的な記述について備忘録としてまとめます。

データバインディング

テキストのバインディング

  • データのバインディグのもっとも基本的な形 マスタッシュ {{ }}を利用したもの
  • 以下のような使い方ができます。
App.vue
 <template lang="pug">
    #app
        span {{ msg }} //hello
 </template>
 <script>
    export default {
        data(){
            return{
                msg:"hello"
        }
    }
 </script>
App.vue
<template lang="pug">
  .app
    span {{inc}} //numに +1された数字がバインディングされる
</template>
<script>
export default {
  data(){
    return{
      num:10
    }
  },
  computed:{
    inc(){
      return this.num + 1
    }
  }
};
</script>

属性のバインディング

  • {{ }}マスタッシュはHTML属性の内部では使えない
  • 代わりに v-bindディレクティブを使用する
App.vue
  <template lang="pug">
    #app
        span(v-bind:class="dynamicClass") {{ msg }}
  </template>
  <script>
    export default {
        data(){
            return{
                msg:"hello",
                dynamicClass:"hoge"
        }
    }
  </script>
  <style>
  .hoge{
    display:inline-block;
  }
  .fuga{
    display:none;
  }
  </style>

dynamicClassの値をhoge⇨fugaに変更すると、spanのクラスが変更され、非表示になります。

親子間のデータの受け渡し

  • Vue.jsでの親子間のデータの受け渡しは、『props down, events up』
  • 親はプロパティを経由してデータを子に伝える
  • 子はイベントを経由して親にメッセージを送る

という認識でいます。

以下のように子コンポーネントでpropsオプションを指定します。

CustomInput.vue
<template>
...
input(type="text" :placeholder="customPlaceholder" @input="updateValue")
...
</template>
<script>
export default = {
 props:{
  customPlaceholder:{
   type:String,
   default:""
  }
 },
 methods: {
  updateValue (e) {
   this.$emit('input', e.target.value)
   this.$emit('change', e.target.value)
   }
  }
}
</script>
CustomInput.vue
this.$emit('input', e.target.value)

この部分で子コンポーネントからinputに入力されたvalueを親に渡しています。

親コンポーネントでは、子に渡すデータを指定、inputEmailの値が子のコンポーネントに渡されます。

Form.vue

<template>
 custom-input(:customPlaceholder="inputEmail")
</template>
<script>
import CustomInput from "./components/CustomInput"
export default = {
  components:{
   CustomInput
 },
 data(){
  return{
   inputEmail: "メールアドレスを入力してください"
  }
 }
}
</script>

だいぶ掻い摘んで書いてみましたが、書き方どうだっけ?的なときのために。

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