vue父子组件传值的三种完整方式

119 阅读1分钟

vue常见的组件传值方式:

  • 父传子
  • 子传父
  • 非父子传值 | 兄弟传值
  1. 父传子
    父组件:
<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>

子组件:

<template>
  <div>
    子组件:
    <span>{{inputName}}</span>
  </div>
</template>
<script>
  export default {
    // 接受父组件的值(注意props请放在最前面)
   
    props:  ["inputName"],
    data()
  }
</script>
  1. 子传父
    子组件
<template>
  <div>
    子组件:
    <span>{{childValue}}</span>
    <!-- 定义一个子组件传值的方法 -->
    <input type="button" value="点击触发" @click="childClick">
  </div>
</template>
<script>
  export default {
    data () {
      return {
        evidence: '我是子组件的数据'
      }
    },
    methods: {
      childClick () {
        // childByValue是在父组件on监听的方法
        // 第二个参数this.childValue是需要传的值
        this.$emit("materials", this.evidence); //触发 input 事件,并传入新值
      }
    }
  }
</script>

父组件

<template>
  <div>
    父组件:
    <span>{{name}}</span>
    <br>
    <br>
    <!-- 引入子组件 定义一个on的方法监听子组件的状态-->
    <child  
    	:third="third"
        @materials="getMaterials">
   </child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    },
    methods: {
      getMaterials(evidence) {
        // childValue就是子组件传过来的值
        this.name = evidence
      }
    }
  }
</script>
  1. 非父子传值 | 兄弟传值 非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中间仓库来传值,不然路由组件之间达不到传值的效果

公共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 () {
        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 () {
      // 用$on事件来接收参数
      Bus.$on('val', elementValue => {
        console.log(elementValue)
        vm.name = elementValue
      })
    },
    methods: {
      getData () {
        this.name++
      }
    }
  }
</script>