vue3 组件之间的数据传递

命运对每个人都是一样的,不一样的是各自的努力和付出不同,付出的越多,努力的越多,得到的回报也越多,在你累的时候请看一下身边比你成功却还比你更努力的人,这样,你就会更有动力。

导读:本篇文章讲解 vue3 组件之间的数据传递,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

父组件向子组件传递数据

子组件test1

<template>
<h>{{myid}}</h>
</template>

<script>
    import {reactive,toRefs} from "vue"
    export default {
        name: "Test1",
        props:["id"],
        setup(props){
            const state=reactive({
                myid:props.id
            })
            return {
                ...toRefs(state)
            }
        }
    }
</script>

父组件test2

<template>
<test1 v-for="item in posts" :key="item.id" :id="item.id"></test1>
</template>

<script>
    import {reactive,toRefs} from "vue"
    import test1 from "./Test1.vue"
    export default {
        name: "Test2",
        components:{
            test1
        },
        setup(){
            const state=reactive({
                posts:[
                    {id:1},
                    {id:2},
                    {id:4}
                ]
            })

            return{
                ...toRefs(state)
            }
        }
    }
</script>

子组件向父组件传递数据

子组件test1

<template>
<button @click="clickbutton">点击按钮</button>
</template>

<script>
    import {reactive,toRefs} from "vue"
    export default {
        name: "Test1",
        setup(props,{emit}){
            const state=reactive({

            })
            const clickbutton=()=>{
                emit("event","我是子组件传过来的数据")
            }
            return {
                ...toRefs(state),
                clickbutton
            }
        }
    }
</script>

父组件test2

<template>
    <test1 @event="handclick">点击</test1>
{{test}}
</template>

<script>
    import {reactive,toRefs} from "vue"
    import test1 from "./Test1.vue"
    export default {
        name: "Test2",
        components:{
            test1
        },
        setup(){
            const state=reactive({
                test:""
            })
            const handclick=(data)=>{
                state.test=data
            }

            return{
                ...toRefs(state),
                handclick
            }
        }
    }
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/143104.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!