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>
相关推荐
旺仔Sec36 分钟前
2026年度河北省职业院校技能竞赛“Web技术”(高职组)赛项竞赛任务
运维·服务器·前端
用户40993225021237 分钟前
Vue的Class绑定对象语法如何让动态类名切换变得直观高效?
前端·ai编程·trae
瘦的可以下饭了1 小时前
Day01-API
javascript
GIS之路1 小时前
GIS 数据转换:GDAL 实现将 CSV 转换为 Shp 数据(一)
前端
Nan_Shu_6141 小时前
学习:Vue (2)
javascript·vue.js·学习
武清伯MVP1 小时前
深入了解Canvas:HTML5时代的绘图利器(一)
前端·html5·canvas
一水鉴天1 小时前
整体设计 定稿 之24 dashboard.html 增加三层次动态记录体系仪表盘 之2 程序 (Q208 之1)
前端·html
北辰alk2 小时前
Vue项目Axios封装全攻略:从零到一打造优雅的HTTP请求层
vue.js
_杨瀚博2 小时前
微信支付集成_JSAPI
前端
polaris_tl2 小时前
react beginwork
前端