1. 程式人生 > >vue 父元件子元件傳值

vue 父元件子元件傳值

1.父元件主動獲取子元件的資料和方法

父元件中呼叫子元件的時候 定義ref

<div class="main-form-body" :style="{'height':isReport == 2 ? '100%' : ''}">
      <component :is="report.component" :params="report.params" ref="headerChild"></component>
</div>

父元件裡使用

this.$refs.headerChild.屬性
this.$refs.headerChild.方法

2.子元件主動獲取父元件的資料和方法

子元件使用
this.$parent.屬性
this.$parent.方法

3.父元件向子元件傳值

父元件: 載入子元件
<template>
  <div>
    <input type="text" v-model="name">
    <br>
    <br>
    <!-- 引入子元件 -->
    <child :inputName="name"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    }
  }
</script>
  子元件: 通過props接收父元件的值
  <template>
  <div>
    <span>{{inputName}}</span>
  </div>
</template>
<script>
  export default {
    // 接受父元件的值
    props: {
      inputName: String,
      required: true
    }
  }
</script>

4.子元件向父元件傳值

子元件: 通過點選事件 發起事件$emit
<template>
  <div>
    <span>{{childValue}}</span>
    <!-- 定義一個子元件傳值的方法 -->
    <input type="button" value="點選觸發" @click="childClick">
  </div>
</template>
<script>
  export default {
    data () {
      return {
        childValue: '我是子元件的資料'
      }
    },
    methods: {
      childClick () {
        // childByValue是在父元件on監聽的方法
        // 第二個引數this.childValue是需要傳的值
        this.$emit('childByValue', this.childValue)
      }
    }
  }
</script>

父元件:on方法監聽,可以在父元件的mounted方法中監聽
<template>
  <div>
    <span>{{name}}</span>
    <!-- 引入子元件 定義一個on的方法監聽子元件的狀態-->
    <child v-on:childByValue="childByValue"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    },
    methods: {
      childByValue: function (childValue) {
        // childValue就是子元件傳過來的值
        this.name = childValue
      }
    }
  }
</script>

5.非父子元件傳值
非父子元件之間傳值,需要定義個公共的公共例項檔案bus.js,作為中間倉庫來傳值,不然路由元件之間達不到傳值的效果。

公共bus.js

A元件:
<template>
  <div>
    <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>
    <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>