vue:父子组件传值

一、父组件传值给子组件

父组件调用子组件时绑定自定义属性,子组件通过props接收。

二、子组件传值给父组件

1、父组件调用子组件时自定义事件,子组件传值时触发该自定义事件。

2、父组件调用子组件时绑定自定义属性,属性是一个函数,子组件传值时直接调用该函数进行传值。

三、代码示例

代码中,App.vue是父组件,One.vue、Two.vue、Three.vue是子组件

它们之间的传值关系:

App.vue传值给One.vue

Two.vue传值给App.vue

Three.vue传值给App.vue

App.vue

<template>
    <div id="app">
    
        <input type="text" ref="in" />
        <button @click="sendAction">按钮</button>
    
        <hr/>
    
        <!-- 父组件传值给子组件 -->
        <!-- 父组件调用子组件时绑定自定义属性,子组件通过props接收。 -->
        <one-com :val="value" />
    
        <hr/>
        
        <!-- 子组件传值给父组件 -->
        <!-- 父组件调用子组件时自定义事件,子组件传值时触发该自定义事件。 -->
        <p>接收到two的值为:{{twoData}}</p>
    
        <two-com @send="handleSend" />
    
        <hr/>
    
        <!-- 子组件传值给父组件 -->
        <!-- 父组件调用子组件时绑定自定义属性,属性是一个函数,
             子组件传值时直接调用该函数进行传值。 -->
        <p>接收到three的值为:{{threeData}}</p>
    
        <three-com :sendAction="handleThreeData" />
      
    </div>
</template>

<script>
import One from './components/One'
import Two from './components/Two'
import Three from './components/Three'
export default {
    data(){
        return {
            value: 'test',
            twoData: null,
            threeData: null
        }
    },
    methods: {
        sendAction(){
            this.value = this.$refs.in.value;
        },
        handleSend(val){
            this.twoData = val;
        },
        handleThreeData(val){
            this.threeData = val;
        }
    },
    components: {
        'one-com': One,
        'two-com': Two,
        'three-com': Three
    }
}
</script>

<style>

</style>

One.vue

<template>
    <div class="one">

        <p>接收到的值为:{{ val }}</p>

    </div>
</template>

<script>
export default {
    props: ['val']
}
</script>

<style>

</style>

Two.vue

<template>
    <div class="two">

        <input type="text" ref="in" />
        <button @click="btnAction">发送</button>

    </div>
</template>

<script>
export default {
    methods: {
        btnAction(){
            let val = this.$refs.in.value;
            // 触发父组件绑定的自定义send事件
            this.$emit('send', val);
        }
    }
}
</script>

<style>

</style>

Three.vue

<template>
    <div class="three">

        <input type="text" ref="in" />
        <button @click="btnAction">发送</button>

    </div>
</template>

<script>
export default {
    props: {
        sendAction: Function
    },
    methods: {
        btnAction(){
            let val = this.$refs.in.value;
            // 直接调用sendAction函数进行传值
            this.sendAction(val);
        }
    }
}
</script>

<style>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值