美文网首页
Vue组件通信,父传子,子传父

Vue组件通信,父传子,子传父

作者: 扣丁李 | 来源:发表于2021-09-28 01:03 被阅读0次

子组件

<template>
    <div>
        <button type="button" @click="count(-1)">-</button>
        <input type="text" :value="num" />
        <button type="button" @click="count(1)">+</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                // num: 0
            }
        },
        props:['num'],
        methods: {
            count(val) {
                this.$emit('num-change',val)
            },
        }
    }
</script>

<style>
</style>

父组件

<template>
    <div id="app">
        <InputNumber :num="num" @num-change="count" />
    </div>
</template>

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

    export default {
        name: 'app',
        components: {
            InputNumber
        },
        data(){
            return{
                num:5
            }
        },
        methods:{
            count(val){
                if (val === -1) {
                    if (this.num > 0) {
                        this.num = this.num + val
                    }
                } else {
                    this.num = this.num + val
                }
            }
        }
    }
</script>

<style>
    #app {
        font-family: 'Avenir', Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
    }
</style>

效果

image.png

总结

子组件接收父组件传值 (props) 子组件传值給父组件($emit())

相关文章