vue的父子组件间传值以及非父子间传值

Vue组件间的传值方式:

 父传子

子传父

非父子间传值

1.首先父组件传值给子组件,使用bind绑定属性,然后在子组件用props接收属性值.

//父组件
<template>
  <input  type="text" />
  <br/>
  <child :inputValue="inputValue"></child>
</template>

<script>
 import child from './Child/child'  
 export default{
   data(){
      return{
       inputValue:'我是父组件'
     }
   },
   components:{
      child
   }

 }

</script>
//子组件child

<template>
    <span> {{inputValue}} </span>
<template>

<script>

  export default {
     props:{
         inputValue:''
      }
   }


</script>

2.子组件传值给父组件,子组件通过绑定点击事件提交this.$emit()方法传值,父组件通过监听来操作传过来的值.

//子组件
<template>
   <div> 
      <span>{{childValue}}</span>
<br> <input type="text" @click="childClick"> </div> <template> <script> export default{ data(){ childValue:'我是子组件' }, methods:{ childClick(){ this.$emit('sub',this.childValue)//第一个参数是父组件监听的函数 ,第二个参数是要传递给父组件的值. } } } </script>

.

//父组件
<template> <span>{{name}}</span> <br> <child @sub="parentEvent"></child> </template> <script> import child from './child' export default{ components:{ child }, data(){ return { Value:'' } }, methods:{ parentEvent(data){ this.Value=data; } } } </script>

3.非父子组件间的传值

通过公共eventBus.js来传值,定义一个新的vue实例专门用来传递数据.

//eventBus.js
import Vue from 'vue';
export default new Vue();
//组件A
<template>
     <button @click="emitToB"></button>
</template>

<script>
 import eventBus from './eventBus'
  export default{
    data(){
      return{
      }
    },
    methods:{
       emitToB(){
         eventBus.$emit('eventA',"我是A传给B的值");  
      }
    } 

 } 


</script>
//组件B
<template>
   <span>{{title}}</span>
</template>

<script>
import eventBus from './eventBus'
 export default{
   data(){
      return {
       title:''
     }
   },    
  mounted(){
    this. getA();
 },
 methods:{
   var that=this;
   getA(){
      eventBus.$on('eventA',function(data){
           that.title=data;
     })   
   }
 }  

 }

</script>

猜你喜欢

转载自www.cnblogs.com/xxcnhj/p/11040569.html