LoginSignup
1
0

More than 3 years have passed since last update.

laraval8 + vue.js2.6で、親子(parent-child)component間の通信について(propsや$emitを使わない場合=>.nativeの使い方)

Last updated at Posted at 2021-01-12

この本を書いたきっかけは?何についての記事?

「これから始める、Vue.js実践入門」(山田祥寛/著、SBクリエイティブ株式会社/発行)のリスト4-16あたりをlaravel8のプロジェクト内でやりたかったので、コードを少し改変してみた。

参考にしたサイトなど

前に挙げた本以外、忘れてしまいました。思い出したら追記するかもです。

前置きはこれくらいにして

MyComponent3.vue
<template>
  <div>
    <div>
      <p>現在値{{ current }}</p>
    </div>
    <mycomponent4 step="1" v-on:click.native="onclick"></mycomponent4>
    <mycomponent4 step="2" v-on:click.native="onclick"></mycomponent4>
    <mycomponent4 step="-1" v-on:click.native="onclick"></mycomponent4>
  </div>
</template>

<script>
import mycomponent4 from './MyComponent4.vue';
export default {
components: {mycomponent4},
 data: function () {
    return {
        current: 0,
    }
 },
  methods: {
    onclick: function (e) {
      this.current += Number(e.target.childNodes[0].nodeValue);
      //console.log(e);
      console.log(Number(e.target.childNodes[0].nodeValue));
    },
  },
};
</script>

.nativeってのがミソで、これがないと動きません。
e.target.childNodes[0].nodeValueってのがボタンに表示されてる値を指すわけですが、
これが正確にどう指定すればよいかはconsole.log(e);してからchromeのdevtoolでeの中身をポチポチ開いていった後に、右クリックで「Copy property path」すると間違いがなくて安心です。

MyComponent4.vue
<template>
<button type="button" v-on:click="onclick">{{ step }}</button>
</template>
<script>
export default {
 data: function () {
    return {
        current: 0,
    }
 },

    props: ['step'],
    methods: {
        onclick:function() {
            this.$emit('plus', Number(this.step));
        }
    }
};
</script>
app.js
require('./bootstrap');
import Vue from 'vue'
import App3 from './components/MyComponent3.vue'
const app3 = new Vue({
    el: '#app3',
    components: {
         App3
    },
});

Controllerとか、実際の画面の動きとかはhttps://qiita.com/tarako2/items/942b1c5d9af9bb4bf946
と一緒なので参考にされてください。
ここまで見ていただいてありがとうございました。何かお役に立てれば幸いです。

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