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>
相关推荐
前端小趴菜052 分钟前
React-React.memo-props比较机制
前端·javascript·react.js
摸鱼仙人~1 小时前
styled-components:现代React样式解决方案
前端·react.js·前端框架
sasaraku.2 小时前
serviceWorker缓存资源
前端
RadiumAg3 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo3 小时前
ES6笔记2
开发语言·前端·javascript
yanlele3 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
中微子4 小时前
React状态管理最佳实践
前端
烛阴4 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
中微子4 小时前
JavaScript 事件与 React 合成事件完全指南:从入门到精通
前端
Hexene...5 小时前
【前端Vue】如何实现echarts图表根据父元素宽度自适应大小
前端·vue.js·echarts