LoginSignup
2
1

More than 3 years have passed since last update.

vue.js component 非同期で 部品化

Last updated at Posted at 2019-07-01

vue.js で component を使いまわしたい時がある。
しかも非同期で。

概要

・各vueから読み込む
<my-component :message="message"></my-component>の中に Com.vue の内容を表示する。
・top.vue から message 池田を渡す。必ず data の中に入れて渡す。

top.vue

<my-component :message="message"></my-component>

<script>

    export default {
        components: {
            'my-component': () => import('./Com.vue')
        },
        data () {
            return {
                //子要素にわたす
                message:'池田'
            };
        },
    }

</script>

com.vue

<template>

    <div>
        ラッキー {{message}}
    </div>

</template>

<script>
    export default {
        props: ['message']
    }
</script>


すると ラッキー 池田 と表示される。

子 から 親 のメソッドを操作

top.vue

<template>
    <div>
        <my-component @taberu="parentsMethod"></my-component>
    </div>
</template>

<script>

    export default {
        components: {
            'my-component': () => import('./MyComponent.vue')
        },
        data() {
            return {
            };
        },
        methods: {

            //これが動く
            parentsMethod() {
                alert('お腹いっぱい')
            }
        }
    };
</script>

com.vue

<template>
    <div>
        <button @click="taberu">親にイベント通知</button>
    </div>
</template>

<script>
    export default {
        methods: {
            taberu(){
                alert("食事開始");
                this.$emit('taberu')
            }
        }
    }
</script>

「食事開始」「お腹いっぱい」 とアラートされる。
また、親側で @taberu="parentsMethod を指定しない場合は親側のメソッドは動作しない。

値の受け渡し


//子
this.$emit('taberu',this.res);

//親
parentsMethod(data) {
                alert(data)
            },

って感じで emit のあとに 渡したい データを入れるだけで渡せる

親の引数を渡すとき、遅延したい場合

例えば親でaxiosを使ってユーザーのIDを読み出して、
子に渡したい場合がある。
しかし、普通にやると undefined になるので、ちょっと工夫。

oya.vue

<note-component :social_id="this.social.id" v-if="this.social.id"></note-component>


<script>

data () {
    return {

        social: {
            id:'',
        },

</script>

これで social.id に値が入ったら note-component を動かせる。

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