Vue中經常使用的三種傳值方式

父傳子

父子組件的關係能夠總結爲prop向下傳遞,事件向上傳遞。父組件經過prop給子組件下發數據,子組件經過事件給父組件發送消息。vue

父組件:工具

<template>
  <div>
    父組件:
    <input type="text" v-model="name">
    <br>
    <br>
    <!-- 引入子組件 -->
    <child :inputName="name"></child>  //child子組件經過 :inputName="name" 將值傳過去
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    }
  }
</script>

子組件:ui

<template>
  <div>
    子組件:
    <span>{{inputName}}</span>
  </div>
</template>
<script>
  export default {
    // 接受父組件的值
    props: {
      inputName: String,   //在這裏對傳過來的進行接收
      required: true
    }
  }
</script>

子傳父

子組件能夠經過$emit觸發父組件的自定義事件。vm.$emit(event,arg) 用於觸發當前實例上的事件;this

子組件:spa

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

父組件:.net

<template>
  <div>
    父組件:
    <span>{{name}}</span>
    <br>
    <br>
    <!-- 引入子組件 定義一個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>

非父子組件傳值

非父子組件之間傳值,須要定義個公共的公共實例文件bus.js,做爲中間倉庫來傳值,否則路由組件之間達不到傳值的效果。code

公共bus.jscomponent

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

組件A:blog

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

本文大部分來自 lander_xiong的CSDN博客,全文地址請點擊:https://blog.csdn.net/lander_xiong/article/details/79018737?utm_source=copy

相關文章
相關標籤/搜索