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>
相关推荐
你的人类朋友1 小时前
什么是API签名?
前端·后端·安全
会豪3 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子3 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶3 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子3 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_4 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
Gracemark4 小时前
高德地图-地图选择经纬度问题【使用输入提示-使用Autocomplete进行联想输入】(复盘)
vue.js
小徐_23334 小时前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin4 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
遂心_4 小时前
深入理解 React Hook:useEffect 完全指南
前端·javascript·react.js