看啥推荐读物
专栏名称: Annie丶
目录
相关文章推荐
今天看啥  ›  专栏  ›  Annie丶

Vue 中父子组件的双向绑定

Annie丶  · 简书  ·  · 2020-02-19 13:36

vue 提供了父子组件间的双向绑定的指令。我这里演示的只是学习使用。使用插槽方式。

子组件代码如下
<template>
    <div>
        <input v-model="msg"><br>
        {{ msg }}
        <!-- 接收来自父组件的插槽,并返回给子组件的 msg 值 -->
        <slot name="slot-name" :slotValue="msg"></slot>
    </div>
</template>

<script>
    export default {
        name: "TwoWayBinding",
        props: {
            msg: {
                type: String,
                default: 'Hello'
            }
        }
    }
</script>

<style scoped>

</style>
父组件
<template>
    <div id="app">
        <h4>父子组件双向绑定</h4>
        <input v-model="msg" ><br>
        {{ msg }}
        <hr>
        <twoWayBinding v-bind:msg="msg">
            <!-- 接收子组件传来的值,并赋值给父组件 -->
            <template v-slot:slot-name="{ slotValue }">
                <span>{{ msg = slotValue }}</span>
            </template>
        </twoWayBinding>
        <h4></h4>
    </div>
</template>

<script>

    import twoWayBinding from "./components/TwoWayBinding";

    export default {
        name: 'App',
        components: {
            twoWayBinding
        },
        data() {
            return {
                msg: 'Hello,World!',
            }
        },
        methods: {

        }
    }
</script>

<style>
    .c1 {
        font-size: 90px;
    }

    .c2 {
        font-size: 10px;
    }
</style>


扩展内容
github
个人博客




原文地址:访问原文地址
快照地址: 访问文章快照