vue父子通讯

父传子

下面是子组件

html 复制代码
<template>
<h1>{{ count }}</h1>
</template>
<script>
expose default {
    name:'HelloWorld',
    props: {
        count:{
            type:[String,Number],
            default:"100"
        }    
    }
}


</script>

子组件使用Props发送

父组件接收:

html 复制代码
<template>
<div id = "app">
    <HelloWorld count = 100></HelloWorld>
</div>
</template>

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

    export default {
        name: 'App',
        components: {
            HelloWorld
        },
    }
}
</script>

子传父

eg:每个商品选中后,把价钱传给父组件,然后结算。

html 复制代码
<template>
<h1>{{ count }}</h1>
<button @click="handler">按钮</button>
</template>
<script>
expose default {
    name:'HelloWorld',
    props: {
        count:{
            type:[String,Number],
            default:"100"
        }    
    },
    data () {
        return {
        childCount: 0
        }
    },
    methods: {
        handler () {
            this.childCount++,
            this.$emit('child-count-change',this.childCount)
        }
    }
}


</script>

父组件:

html 复制代码
<template>
<div id = "app">
    <HelloWorld count = 100,@child-count-change="handler"></HelloWorld>
    <h1>{{ childData }}</h1>
</div>
</template>

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

    export default {
        name: 'App',
        components: {
            HelloWorld
        },
        data () {
            childData: 0
        }
        methods: {
            handler (childCount) {
                this.childData = childCount
            }
        }
    }

</script>
相关推荐
三小河6 分钟前
Agent Skill与Rules的区别——以Cursor为例
前端·javascript·后端
Hilaku12 分钟前
不要在简历上写精通 Vue3?来自面试官的真实劝退
前端·javascript·vue.js
三小河19 分钟前
前端视角详解 Agent Skill
前端·javascript·后端
Aniugel32 分钟前
单点登录(SSO)系统
前端
颜酱32 分钟前
二叉树遍历思维实战
javascript·后端·算法
鹏多多35 分钟前
移动端H5项目,还需要react-fastclick解决300ms点击延迟吗?
前端·javascript·react.js
serioyaoyao37 分钟前
上万级文件一起可视化,怎么办?答案是基于 ParaView 的远程可视化
前端
万少43 分钟前
端云一体 一天开发的元服务-奇趣故事匣经验分享
前端·ai编程·harmonyos
WindrunnerMax1 小时前
从零实现富文本编辑器#11-Immutable状态维护与增量渲染
前端·架构·前端框架
不想秃头的程序员1 小时前
Vue3 封装 Axios 实战:从基础到生产级,新手也能秒上手
前端·javascript·面试