vue组件传值

vue组件传值-------总结

1·父组件传值子组件

父组件通过   :paramsName1="params1" :paramsName2="params2"的方式将值传递给子组件
子组件通过    props接收参数
    props{
        paramsName1{
            type:string,
            default:"默认参数1"
        },
        paramsName2{
            type:string,
            default:"默认参数2"
        }
    }
    得到传递过来的参数就可以使用了
    
    方法的传递:
    在父组件定义一个方法 将他绑定在子组件上   @click="theWays"
    
    methods:{
        theWays(params){
            alert("这里是具体方法")
        }
    }
    
    在子组件内绑定theWays方法
    
        @click="showTheWay"
        
        methods:{
            showTheWay(){
                使用$emit接收父组件的方法
                this.$emit("theWays")
            }
        }
        
        
        
    2·子组件传值父组件
    
    在子组件定义方法 @click="sendToParent"
    data(){
        return{
        sendvaluetop:"发送到父组件"    
        }
    }
    methods:{
        sendToParent(){
            //使用$emit传递
            this.$emit("getChildValue",this.sendvaluetop)//第一个参数代表父组件的方法,第二个参数代表子组件传递的值
        }
    }
    
    
    在父组件将方法  :getChildValue="getChild" 或  v-on:getChildValue="getChild"  绑定到子组件上
    data(){
        return {
            ChildValue:'',//用来接收子组件的参数
        }
    }
    methods:{
        getChild(getvalue){
            this.ChildValue = getvalue//获取子组件传递的值
        }
    }
    
    
    3非父子组件传值
    
    A组件传值  B组件获取值
    
    在A组件定义
    data(){
        return{
            sendMsg:"这是发送的数据"
        }
    }
        this.$emit("sendToB",this.sendMsg);//第一个参数为 AB两个组件共同的事件名字,第二个参数为A发送的数据
        
    在B组件定义
    data(){
        return{
            getMsg:""
        }
    }
        VM.$on('事件名',callback)    --------------------callback回调$emit要传送的数据;
        this.$on("sendToB",(res)=>{
            this.getMsg = res; //得到A传的值
        });//第一个参数为 AB两个组件共同的名字,第二个参数为A发送的数据

你可能感兴趣的:(vue,组件之间传值)