【Vue学习笔记】—— 组件之间传递数据 { }

2020-12-20  本文已影响0人  Curry_Ming

学习笔记

Vue 组件
1.通过绑定传递数据(父组件 ——》 子组件)
<div id="app">
    <father></father>
</div>

<template id="father">
    <div>
        <h1>father:{{ fatherMsg.name }} -- {{ fatherMsg.age }}</h1>
        <son :faobj='fatherMsg'></son>
    </div>
</template>
<template id="son">
    <div>
        <input type="button" @click='getFather' value="获取一个父亲">
        <h1>小头儿子:my father -- {{ faobj.name }} -- {{ faobj.age }}</h1>
    </div>
</template>
Vue.component('father', {
    template: '#father',
    data: function () {
        return {
            fatherMsg: {
                name: '小头爸爸',
                age: '21'
            }
        }
    },
    components: {
        son: {
            template: '#son',
            data: function () {
                return {
                    fobj: {
                        name: '',
                        age: ''
                    }
                }
            },
            props: ['faobj'],
            methods: {
                getFather() {
                    this.fobj = this.faobj
                }
            }
        }
    }
})
new Vue({
    el: "#app",
})
2.通过事件传递数据 (子组件 ——》 父组件)
<div class="app">
    <father></father>
</div>
<template id="father">
    <div>
        <h1>father: mySon -- {{ sonObj.name }} -- {{ sonObj.age }}</h1>
        <son @stof='getSon'></son>
    </div>
</template>
<template id="son">
    <div>
        <h1>son: {{ sobj.name }} -- {{ sobj.age }}</h1>
        <input type="button" value="投入到父亲的怀抱" @click='sonToFather'>
    </div>
</template>
Vue.component('father', {
    template: '#father',
    data: function () {
        return {
            sonObj: {
                name: '',
                age: ''
            }
        }
    },
    methods: {
        getSon(son) {
            this.sonObj = son
        }
    },
    components: {
        son: {
            template: '#son',
            data: function () {
                return {
                    sobj: {
                        name: '大耳朵图图',
                        age: '1'
                    }
                }
            },
            methods: {
                sonToFather() {
                    this.$emit('stof', this.sobj)
                }
            }
        }
    }
})

new Vue({
    el: ".app",
})
上一篇 下一篇

猜你喜欢

热点阅读