vue props 的取对象中的counts中 的值

版权声明:独学而无友,则孤陋寡闻。q群582951247 https://blog.csdn.net/mp624183768/article/details/88074590

前些课程我们已经用过 

props做了一个++的样例
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
    <title>Component</title>
    <style>
        #app {
            margin: 1em;
            font-size: 1.2em;
        }
        .component {
            margin-bottom: 1em;
        }
    </style>
</head>

<body>
<div id="app">
    <div>count of parent:{{counts}}</div>
    <br>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>


</div>
<script>
    Vue.component('my-component',{
        template:' <div class="component"> <span>{{count}}</span>- <button @click="count++">add</button></div>',
        props:['count']
    });

    new Vue({
        el:'#app',
        data:{
            counts:0
        }
    });
</script>

</body>
</html>

但是存在一种常见的情况。data中的counts是一个对象

我们再次编辑的时候

<body>
<div id="app">
    <div>count of parent:{{counts}}</div>
    <br>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>
    <my-component :count="counts"></my-component>


</div>
<script>
    Vue.component('my-component',{
        template:' <div class="component"> <span>{{count.num}}</span>- <button @click="count.num++">add</button></div>',
        props:['count']
    });

    new Vue({
        el:'#app',
        data:{
            counts:{
                num:0
            }
        }
    });
</script>

</body>

会发现都变成了成员变量

如何修正呢

<script>
    Vue.component('my-component',{
        template:' <div class="component"> <span>{{c}}</span>- <button @click="c++">add</button></div>',
        props:['count'],
        data(){
            return {c:this.count.num}
        }
    });

    new Vue({
        el:'#app',
        data:{
            counts:{
                num:0
            }
        }
    });
</script>

多加一个data属性再应用一个c变量即可解决

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/88074590
今日推荐