vue2.0 父子组件传值

父组件传值给子组件

子组件


<template>

  <div>

    <div>{{innertext}}</div>   

  </div>

</template>

<script>

    export default{

        name:'hello',

        // props:String 只定义类型

        props:{

            innertext:{            
                 type:String,

                 default:'456'      // 可以定义默认值
              }
        }

    }

</script>

子组件通过 props 接收值

父组件


<template>

  <div id="app">

    <hello :innertext="content"></hello>

  </div>

</template>

<script>

    import hello from "@/components/hello";

    export default{

        components:{

            hello

        },

        data(){

            return{

                content:'123'

            }

        }

    }

</script>

父组件通过标签属性传值

子组件传值给父组件

子组件


<template>

  <div>

    <div @click="componentEmit">{{innertext}}</div>   

  </div>

</template>

<script>

    export default{

        name:'hello',

        methods:{

            componentEmit(){

                this.$emit('componentClick',date)

            }

    }

    }

</script>

子组件通过 $emit 自定义事件传值

父组件


<template>

  <div id="app">

    <hello @componentClick="eleClick"></hello>

  </div>

</template>

<script>

    import hello from "@/components/hello";

    export default{

        components:{

            hello

        },

        data(){

            return{

            }

        },

        methods:{

            eleClick(e){

                /**

                e 是 子组件点击触发后传过来的值

                */

            }

        }

    }

</script>

父组件通过接受自定义事件接收值

sync 修饰符

子组件


<template>

  <div>

    <div @click="updateEvent">{{innertext}}</div>   

  </div>

</template>

<script>

    export default{

        name:'hello',

        props:{

          innertext:String 

        },

        methods:{

            updateEvent(){

                this.$emit("update:innertext",'789')

            }

    }

    }

</script>

父组件


<template>

  <div id="app">

    <hello :innertext.sync="content"></hello>

  </div>

</template>

<script>

    import hello from "@/components/hello";

    export default{

        components:{

            hello

        },

        data(){

            return{

                content:'123'

            }

        },

        methods:{



        }

    }

</script>

点击促发后content数据会变成子组件传的值

将原生事件绑定到子组件


<template>

<div>

        <hello @click.native="eventClick"></hello>

    </div>

</template>

<script>

    export default{

        methods:{

            eventClick(){

                /**

                  do something

                */

            }

        }

    }

</script>

在子组件使用原生事件在事件名后面加 .native

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容