8.父子组件的数据传递

2018-07-07  本文已影响19人  yaoyao妖妖

1.父组件通过属性向子组件传递参数,子组件用props接收,但是在vue中只可以用,不可以直接修改,这就是单向数据流的概念;
2.如何解决这个问题,就是在子组件的data中重新定义一个变量接收并返回这个值,使用的时候使用这个新定义的属性 。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>父子组件间的数据传递</title>
    <!--引入/vue.js-->
    <script src="./vue.js"> </script>
</head>
<body>
   <div id="root">
       <counter :count="1"></counter>
       <counter :count="2"></counter>

   </div>

   <script>

       //局部组件
       var counter = {
           props:['count'],
           data:function(){
               return {
                   number: this.count

               }
           },
           template:'<div @click="handleClick">{{count}}</div>',
           methods:{
               handleClick:function()
               {
                   this.number ++
               }
            } 
        }


       var app = new Vue({
           el:'#root', 
           components:{
            counter:counter
           },
           data:{
               total:0

           }       
       })

   </script>

</body>

</html>

子组件通过向外触发事件($emit)来告诉父组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>父子组件间的数据传递</title>
    <!--引入/vue.js-->
    <script src="./vue.js"> </script>
</head>
<body>
   <div id="root">
       <counter :count="1" @inc="handleIncrese"></counter>
       <counter :count="2" @inc="handleIncrese"></counter>
       <div> {{total}}</div>

   </div>

   <script>

       //局部组件
       var counter = {
           props:['count'],
           data:function(){
               return {
                   number: this.count

               }
           },
           template:'<div @click="handleClick">{{count}}</div>',
           methods:{
               handleClick:function()
               {
                   this.number ++;
                   this.$emit('inc',1)
               }
            } 
        }


       var app = new Vue({
           el:'#root', 
           components:{
            counter:counter
           },
           data:{
               total:5

           },
           methods:{
            handleIncrese:function(step){
               this.total +=step
            }
           }
         
       })

   </script>

</body>

</html>

上一篇 下一篇

猜你喜欢

热点阅读