vue组件间传值

父组件向子组件传递数据

// 父组件传递
<dialogAttendee :dialogcascaderVisible="dialogcascaderVisible"></dialogAttendee>

// 子组件接接收
props:{  
    dialogcascaderVisible: {
        type: Boolean,
        default: false
    },
    reservation: Array,
}

// 使用props
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

props: {
    title: String,
    likes: Number,
    isPublished: Boolean,
    commentIds: Array,
    author: Object
}

props:{
    propA:{
        type : String,   // 可以是多个类型 [Number, String]
        required : true, // 表示是否必填
        default : "abc", // 默认值
        // 或 default : function(){
        //     return { message : "hello" }  // 默认值可以是对象或数组,它需要从一个工厂函数返回
        // },
        validator:function(value){   // 自定义校验函数
            //这个值必须匹配下列字符串中的一个
            return ['success','warning','danger'].indexof(value) !== -1;
        }
    }
}

父组件改变子组件中的数据

// 父组件中引用子组件
<son ref="son"></son>

// 父组件的点击事件
clickFunc(){
    // 更新子组件里a的值
    this.$refs.son.a = 'xx';
    // 调用子组件里b方法
    this.$refs.son.b();
}

子组件调用父组件方法并向父组件传值

// 子组件触发事件
this.$emit('emitEvent', '123');

// 父组件
// 引用子组件并绑定方法
<part-template @emitEvent = "ievent"></i-template>
// 设置方法
methods:{
    ievent(data){
        console.log('allData:', data); 
    }
}

v-modle实现父子组件传值

model对象有两个属性prop,event;
一个组件上的v-model会把input框的value用作prop;把input或change(可能还有其他)用作event;

model: {
    prop: ‘value1’, 
    // 在该组件被使用(被父组件调用)时,v-model的值绑定给value1;
    event: ‘change’ 
    // emit(触发)change的时候,参数的值就是父组件v-model收到的值;
  },
// 父组件
<template>
  <div id="app">
    <HelloWorld v-model="showFlag" v-if="showFlag"></HelloWorld>
    <button @click="showFlag=true">打开组件</button>
  </div>
</template>

<script>
    import HelloWorld from './components/HelloWorld'

    export default {
    name: 'App',
    data(){
        return {
        showFlag: false
        }
    },
    components: {
        HelloWorld
    }
    }
</script>

//子组件
<template>
  <div class="hello">
    <h1>这是组件里面的内容</h1>
    <button @click="close">关闭组件</button>
  </div>
</template>

<script>
    export default {
    name: 'HelloWorld',
    model: {
        prop: 'checked',
        event: 'change'
    },
    props: {
        checked: {
            type: Boolean
        }
    },
    methods: {
        close(){
        this.$emit('change', false);    // false会赋值给父组件v-modle的值,这里父组件的v-model="showFlag"里的showFlag赋值为false
        }
    }
}

兄弟组件间传值

1 vuex

2 eventBus

// eventBus.js文件
import Vue from 'vue';  
export default new Vue(); 

// 使用的组件首先引用这个文件
import Bus from '../../assets/js/eventBus'

// 引用之后绑定函数,或触发已绑定的函数
// 绑定事件
Bus.$on('setData', param => {
    this.initShare(shareInfo,this);
}); 
// 触发时间
Bus.$emit('setData', 1); 
原文地址:https://www.cnblogs.com/xjy20170907/p/12672379.html