子传父,父传子案例

案例一:
效果图:

未点击:
12039799-352d95df69434446.png
QQ截图20180922100515.png

点击后:
12039799-07920e6518da763f.png
QQ截图20180922100607.png

body:

<div id="app">
   <my-father></my-father>
</div>

js:

<script>
    Vue.component('my-father',{
        template:
        `
            <div>
                <h1>我是父组件</h1>
                <p>子组件添加的值在这里{{mes}}</p>
                <my-child @send='sent'></my-child>
            </div>
        `,
        data:function(){
            return{
                mes:''
            }
        },
        methods:{
            sent:function(text){
                this.mes=text
            }
        }
    })
    
    Vue.component('my-child',{
        template:
        `
            <div>
                <input type='text' v-model='message'>
                <button @click='add'>添加</button>
            </div>
        `,
        data:function(){
            return{
                message:''
            }
        },
        methods:{
            add:function(){
                this.$emit('send',this.message)
            }
        }
    })
    
    new Vue({
        el:'#app'
    })
</script>

案例二:
效果图:

未点击:
12039799-82a2cce97d63d946.png
QQ截图20180922101859.png

点击后:
12039799-01ad984a19803080.png
QQ截图20180922102102.png

body:

<div id="app">
   <my-father></my-father>
</div>

js:

<script>
    Vue.component('my-father',{
        template:`
            <div>
                <p>我是父组件</p>
                <my-child v-bind:number='mes' @send='jssend'></my-child>
                <b>{{text}}</b>
            </div>
        `,
        data:function(){
            return{
                mes:'123',
                text:''
            }
        },
        methods:{
            jssend:function(txt){
                this.text=txt
            }
        }
    })
    
    Vue.component('my-child',{
        props:['number'],
        template:`
            <div>
                <p>{{number}}</p>
                <button @click='add'>点击</button>
            </div>
        `,
        data:function(){
            return{
                num:1
            }
        },
        methods:{
            add:function(){
                this.$emit('send',this.num)
            }
        }
    })
    
    new Vue({
        el:'#app'
    })
</script>

猜你喜欢

转载自blog.csdn.net/weixin_33686714/article/details/87232887