父子组件间的传值

  1. 父组件向子组件传值 (props)
<body>
    <div id="app">
        <father></father>
    </div>
    <script>
        //创建一个父组件
        Vue.component('father', {
            template: `<div>我是父组件,给儿子取名为{{mySonName}}          
                <son :myName='mySonName'></son>
                </div>`,
            //2.在使用子组件的地方,通过v-bind指令给子组件中的props赋值  
            data() {
                return {
                    mySonName: '小明',
                }
            },
            //通过components属性创建子组件
            components: {
                //创建一个子组件
                son: {
                    template: `<div>我是子组件,我的父亲给我取名为{{myName}}</div>`,
                    props: ['myName']
                        //1.声明props,用来接收从父组件传递过来的值。props可以跟一个数组,数组里面的值是一个个的字符串,这个字符串可以当成属性来使用
                }
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {

            }
        })
    </script>
</body>
  1. 子组件向父组件传值 ($emit)
<body>
    <div id="app">
        <father></father>
    </div>
    <script>
        Vue.component('father', {
            template: `<div>
                我是父组件,我的儿子告诉我他叫{{mySonName}}
                <son @tellFatherMyName=getSonName></son>
                </div>`,
            data() {
                return {
                    mySonName: '?'
                }
            },
            methods: {
                //这个函数中有一个默认参数,该参数就是表示上传上来的值
                getSonName(data) {
                    this.mySonName = data
                }
            },
            components: {
                son: {
                    template: `<button @click='tellName'>点击告诉我父亲,我叫{{myName}}</button>`,
                    data() {
                        return {
                            myName: '小明'
                        }
                    },
                    methods: {
                        tellName() {
                            //子组件传值给父组件用$emit()方法,这个方法可以传递两个参数,一个是事件名称,一个是需要传递的数据
                            this.$emit('tellFatherMyName', this.myName)
                        }
                    }
                }
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {}
        })
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/weixin_42442123/article/details/85775291