vue 单向数据流,不应该更改父组件传过来的数据

那么按照标题这样的话,就如同是 这样 data(){name:this.dataf}  this.dataf就是父组件的值  然后把这个值 相当于赋值给 name: this.dataf 然后更改组件里面的data 数据就好了

 

看例子

 

<body>
        <div id="app">
            <h3>父组件中使用了count</h3>
            <p>{{count}}</p>
            <custom-component :count="count" @increment-click="countHandle"></custom-component>
        </div>
        <script>

        //自定义事件

            //全局组件
            //count传入的类型为Number
            Vue.component('custom-component',{
                props:{
                    count:{
                        //type:Number,
                        //type:[Number,String],
                        //default:10
                        //required:true
                        validator:function (value){
                            console.log(value); 

                            return value > 10
                        }
                    }
                },
                data(){
                    return {
                        incrementCount:this.count //作为局部这个组件的data的初始值
                    }
                },
                computed:{
                    incrementCount2(){
                        return this.incrementCount
                    }
                },
                template:`
                    <div>
                        <h2>我是一个自定义的组件</h2>
                        <input type="button" value="改变count的值" @click="changeCount" />
                        {{incrementCount2}}
                    </div>
                `,
                methods:{
                    changeCount(){
                        this.incrementCount++;
                        //通知父组件 发生了改变
                        this.$emit("increment-click")   
                    }
                }
            })

            new Vue({
                el:"#app",
                data:{
                    count:20
                },
                methods:{
                    countHandle(){
                        //alert("子组件点击了");
                        this.count++;
                    }
                }
            })
        </script>
    </body>
posted @ 2018-01-06 20:35  有二度  阅读(335)  评论(0编辑  收藏  举报