avatar
fireworks99
keep hungry keep foolish

Vue :childProps.sync='parentData'

Description

Vue中,父组件通过props向子组件传递数据,如果子组件想要修改这一数据,只能通过$emit触发父组件的一个事件,在这个事件的处理方法中修改这个值。

现在有一种方法可以省略父组件中的这个method:

<cpn :childProps.sync='parentData'></cpn>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- <cpn :num="count" @update:num="setCount"></cpn> -->
        <cpn :num.sync="count"></cpn>
    </div>

    <script>

        const Cpn = {
            template: `<div>
                            {{this.num}}
                            <button @click="inc">count = 2</button>
                        </div>`,
            props: ['num'],
            methods: {
                inc() {
                    this.$emit("update:num", 2);
                }
            }
        }


        const app = new Vue({
            el: "#app",
            data() {
                return {
                    count: 0
                }
            },
            components: {
                Cpn
            },
            methods: {
                setCount(value) {
                    this.count = value;
                }
            }
        })
    </script>
</body>

</html>
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy