1. 程式人生 > >Vue2.0的三種常用傳值方式、父傳子、子傳父、非父子組件傳值

Vue2.0的三種常用傳值方式、父傳子、子傳父、非父子組件傳值

組件 inf rop 發送消息 scrip bug 監聽 bus class

Vue常用的三種傳值方式有:

  • 父傳子

  • 子傳父

  • 非父子傳值


引用官網的一句話:父子組件的關系可以總結為 prop 向下傳遞,事件向上傳遞。父組件通過 prop 給子組件下發數據,子組件通過事件給父組件發送消息

1. 父組件向子組件進行傳值

技術分享圖片

父組件:

<template>
  <div>
    父組件:
    <input type="text" v-model="name">
    <!-- 引入子組件 -->
    <child :abc="name"></child>
  </div>
</template>
<script>
  import child 
from ./child export default { components: { child }, data () { return { name: ‘‘ } } } </script>

子組件:

<template>
  <div>
    子組件:
    <span>{{abc}}</span>
  </div>
</template>
<script>
  export default {
    
// 接受父組件的值 props:[‘abc] } </script>

2. 子組件向父組件傳值

技術分享圖片

<template>
  <div>
    子組件:
    <span>{{childValue}}</span>
    <!-- 定義一個子組件傳值的方法 -->
    <input type="button" value="點擊觸發" @click="send">
  </div>
</template>
<script>
  export default
{ data () { return { childValue: 我是子組件的數據 } }, methods: { send() {
     //第一個參數自定義abc的函數
//第二個參數this.childValue是需要傳的值 this.$emit(‘abc, this.childValue) } } } </script>

父組件:

<template>
  <div>
    父組件:
    <span>{{name}}</span>
    <br>
    <br>
    <!-- 引入子組件 定義一個on的方法監聽子組件的狀態-->
    <child v-on:abc="get"></child>//觸發自定義abc的函數,此處的自定義abc的函數就是get函數
  </div>
</template>
<script>
  import child from ./child
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ‘‘
      }
    },
    methods: {
      get: function (childValue) {
        // childValue就是子組件傳過來的值
        this.name = childValue
      }
    }
  }
</script>

3. 非父子組件進行傳值

公共bus.js

//bus.js
import Vue from vue
export default new Vue()

組件A:

<template>
  <div>
    A組件:
    <span>{{elementValue}}</span>
    <input type="button" value="點擊觸發" @click="elementByValue">
  </div>
</template>
<script>
  // 引入公共的bug,來做為中間傳達的工具
  import Bus from ./bus.js
  export default {
    data () {
      return {
        elementValue: 4
      }
    },
    methods: {
      elementByValue: function () {
        Bus.$emit(val, this.elementValue)
      }
    }
  }
</script>

組件B:

<template>
  <div>
    B組件:
    <input type="button" value="點擊觸發" @click="getData">
    <span>{{name}}</span>
  </div>
</template>
<script>
  import Bus from ./bus.js
  export default {
    data () {
      return {
        name: 0
      }
    },
    mounted: function () {
      var vm = this
      // 用$on事件來接收參數
      Bus.$on(val, (data) => {
        console.log(data)
        vm.name = data
      })
    },
    methods: {
      getData: function () {
        this.name++
      }
    }
  }
</script>

Vue2.0的三種常用傳值方式、父傳子、子傳父、非父子組件傳值