2
3

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.

Vue.js基本文法2

Last updated at Posted at 2019-05-18

Vueの基本構成

new Vue({
    el:"#app",//mountする要素
    data:{//データ
        num1:2,
        num2:3
    },
    computed:{//算出プロパティ
        calc(){
            return this.num1 + this.num2
        }
    },
    mounted(){//ライフサイクルフック系をいろいろ書く

    },
    methods:{//自由に作るメソッド
        hogeMethod(){

        }
    }
})

 ライフサイクルフック一覧

メソッド名 タイミング
beforeCreate インスタンスが作成されて、リアクティブの初期化される前
created インスタンスが作成され、リアクティブの初期化がされた後
beforeMount インスタンスがマウントされる前
mounted インスタンスがマウントされた後
beforeUpdate DOMが再描画される前に呼ばれる
updated DOMが再描画された後に呼ばれる
beforeDestroy インスタンスが破棄される前に呼ばれる
destroyed インスタンスが破棄された後

データバインディング

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

index.html
    <p>{{message}}</p>
    data:{//データ
        message:'Hello Vue.js'
    },

属性のデータバインディング

ダメな例
    <input type="text" value="{{message}}">
正しくはこっち
    <input type="text" v-bind:value="message">

:valueと書いても良い

リストデータの表示と更新

まずは表示

main.js
    data:{//データ
        list:[
            {name:"hogehoge1",mail:"hoge1@example.com"},
            {name:"hogehoge2",mail:"hoge2@example.com"},
            {name:"hogehoge3",mail:"hoge3@example.com"},
        ]
    },
index.html
    <ul>
        <li v-for="item in list">{{item.name}}</li>
    </ul>

リストの更新について

 this.list = []//プロパティの更新なのでOK
 this.list[0].name = 'hogehoge4' //プロパティの更新なのでOK
 this.list[0] = 'hogehoge4' //配列要素の更新なのでNG

インデックス数値を使った配列要素の更新は検知できない
後から追加されたプロパティの更新も検知できない

インデクス数値を使った配列要素の更新は検知できないので
Vue.setメソッドを使用して明示的に更新する

  this.$set(list,0, {name:'new hogehoge', mail:'hoge@example.com'})

第1引数が更新するデータ、第2引数がインデックスもしくはキー、第3引数が値

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?