LoginSignup
3
2

More than 3 years have passed since last update.

Vue.jsで親から子のコンポーネントにデータを渡す方法4つ

Last updated at Posted at 2020-02-03

props、$children、ref、slotがある。

props

<!DOCTYPE html>
<title>props</title>

<div id="app">
  <app-component v-bind:message="parentMessage"></app-component>
  <button v-on:click="onClick">クリック</button>
</div>

<script src="https://unpkg.com/vue@2.5.17"></script>

<script>
Vue.component('app-component', {
  template: '<h1>{{ message }}</h1>',
  props: {
    message: {
      type: String,
      default: 'これは子のコンポーネント'
    }
  }
})

new Vue({
  el: '#app',
  data: {
    parentMessage: '親から渡してるよ'
  },
  methods: {
    onClick: function () {
      this.parentMessage = 'クリックしたら変わるよ'
    }
  }
})
</script>

$children

<!DOCTYPE html>
<title>$children</title>

<div id="app">
  <app-component></app-component>
  <button v-on:click="onClick">クリック</button>
</div>

<script src="https://unpkg.com/vue@2.5.17"></script>

<script>
Vue.component('app-component', {
  template: '<h1>{{ message }}</h1>',
  data: function () {
      return {
        message: 'これは子のコンポーネント'
      }
  }
})

new Vue({
  el: '#app',
  methods: {
    onClick: function () {
      this.$children[0].message = 'クリックしたら親から渡すよ'
    }
  }
})
</script>

$children に対して順序の保証がなく、リアクティブでないことに注意してください。

公式ドキュメント https://jp.vuejs.org/v2/api/index.html#vm-children より引用。

ref

<!DOCTYPE html>
<title>ref</title>

<div id="app">
  <app-component ref="ac"></app-component>
  <button v-on:click="onClick">クリック</button>
</div>

<script src="https://unpkg.com/vue@2.5.17"></script>

<script>
Vue.component('app-component', {
  template: '<h1>{{ message }}</h1>',
  data: function () {
      return {
        message: 'これは子のコンポーネント'
      }
  }
})

new Vue({
  el: '#app',
  methods: {
    onClick: function () {
      this.$refs.ac.message = 'クリックしたら親から渡すよ'
    }
  }
})

</script>

slot

<!DOCTYPE html>
<title>slot</title>

<div id="app">
  <app-component><h1 slot="message">{{ parentMessage }}</h1></app-component>
  <button v-on:click="onClick">クリック</button>
</div>

<script src="https://unpkg.com/vue@2.5.17"></script>

<script>
Vue.component('app-component', {
  template: '<div><slot name="message">これは子のコンポーネント</slot></div>'
})

new Vue({
  el: '#app',
  data: {
    parentMessage: '親から渡してるよ'
  },
  methods: {
    onClick: function () {
      this.parentMessage = 'クリックしたら変わるよ'
    }
  }
})
</script>
3
2
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
3
2