美文网首页
vue父子组件传值

vue父子组件传值

作者: 3e2235c61b99 | 来源:发表于2020-12-07 17:38 被阅读0次

    当不同的页面需要使用相同的元素时,封装子组件会是个好办法

    1.首先定义一个子组件
    2.然后在父组件中引入子组件,并在components中声明这个子组件
    import MyChild from "./child"
    export default {
        components:{
            MyChild
        },
    }
    
    3.在父组件中通过v-bind(或简写为 : )给子组件绑定在子组件中需要使用的值
    <my-child :deliverParentAge="parentAge" :testObj="person" :testArr="peosonList"></my-child>
    
    4.在子组件中通过props接收父组件传过来的值
    props: {
        deliverParentAge: Number,
        testObj: {
            type: Object,
            default: () => {
                return {}
            }
        },
        testArr: {
            type: Array,
            default: () => {
                return []
            }
        }
    },
    
    5.在子组件中通过this.$emit()触发一个事件,并将值传递给父组件
    DiffAge() {
        this.$emit("differAge", this.childAge)
    }
    
    6.父组件通过事件接收子组件通过this.$emit()触发事件传递过来的值
    <my-child @differAge="handleDifferAge"></my-child>
    
    handleDifferAge(child) {
        console.log(`父组件的值为: ${this.parentAge},子组件的值为: ${child}`)
        console.log(`两者相差: ${ this.parentAge - child }`)
    },
    

    另:

    1.子组件通过props接收数据时,最好设置数据类型和初始值

    1.他们写明了组件的API,所以很容易看懂组件的语法
    2.在开发环境下,如果向一个组件提供格式不正确的prop,Vue将会告警,以帮助你捕获潜在的错误

    2.本例中的子组件为单独引入,也可以把子组件全局挂载

    1.在components目录下新建index.js,
    2.在components/index.js中引入组件并挂载

    import detailHeader from './DetailHeader'
    import detailContent from './DetailContent'
    
    export default {
      install: function(Vue) {
        Vue.component('detail-header', detailHeader)
        Vue.component('detail-content', detailContent)
      }
    }
    

    3.在main.js中引入components/index.js并挂载

    import Vue from 'vue'
    import Component from '@/components'
    Vue.use(Component)
    

    ===========================分割线==========================
    完整代码如下:
    parent.vue

    <template>
        <div>
            <h3>我是父组件,我想告诉我的子组件,我的年龄值是:{{parentAge}}</h3>
            <h3>我要通过v-bind(即简写":")语法糖绑定一个属性parentAge,告诉子组件我的年龄值是:{{parentAge}}</h3>
            <!-- 下面就是我的子组件 -->
            <my-child :deliverParentAge="parentAge" :testObj="person" :testArr="peosonList" @addParentAge="handleAddParentAge" @differAge="handleDifferAge"></my-child>
            <h3>通过监听子组件提交的事件addParentAge,我知道到了自己的实际年龄应该是:{{parentAge+1}},并通过方法handleAddParentAge,在控制台打印出我的真实年龄</h3>
        </div>
    </template>
    
    <script>
        import MyChild from "./child"
        export default {
            components:{
                MyChild
            },
    
            data() {
                return {
                    parentAge: 50,
                    person: {
                        name: "明妃",
                        age: 18,
                        sex: "男"
                    },
                    peosonList:[]
                }
            },
    
            created() {
                this.init()
            },
    
            methods: {
                init() {
                    for (let i = 0; i < 10; i++) {
                        this.peosonList.push(this.person)
                    }
                },
    
                handleAddParentAge(actualAge) {
                    console.log(`父组件从子组件获取到的值为: ${actualAge}`)
                    this.parentAge = actualAge
                },
    
                handleDifferAge(child) {
                    console.log(`父组件的值为: ${this.parentAge},子组件的值为: ${child}`)
                    console.log(`两者相差: ${ this.parentAge - child }`)
                },
            }
        }
    </script>
    
    <style>
    </style>
    

    child.vue

    <template>
        <div class="childCase">
            <h5>我是子组件,我可以通过属性props来接收父组件传过来的年龄值是:{{deliverParentAge}},这是一个数字类型</h5>
            <h5>现在我要告诉父组件,我的年龄是{{childAge}},这样他就可以知道,我们<button @click="DiffAge">相差</button>多少岁</h5>
            <h5>并且,我要告诉他,他今年生日已经过了,所以他的年龄应该<button @click="AddAge">加1</button></h5>
            <div>父组件对象的名字: {{ testObj.name }}</div>
        </div>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    childAge: 18
                }
            },
    
            props: {
                deliverParentAge: Number,
                testObj: {
                    type: Object,
                    default: () => {
                        return {}
                    }
                },
                testArr: {
                    type: Array,
                    default: () => {
                        return []
                    }
                }
            },
    
            computed: {
                parentActualAge() {
                    return this.deliverParentAge + 1
                }
            },
    
            created() {
                this.init()
            },
    
            methods: {
                init() {
                    console.log(`父组件对象的名字: ${this.testObj.name}`)
                    console.log(`父组件传过来的对象 `, this.testObj)
                    console.log(`父组件传过来的数组`, this.testArr)
                },
    
                AddAge() {
                    this.$emit("addParentAge", this.parentActualAge)
                },
    
                DiffAge() {
                    this.$emit("differAge", this.childAge)
                }
            }
        }
    </script>
    
    <style scoped>
        .childCase{
            background: pink;
        }
    </style>
    
    

    相关文章

      网友评论

          本文标题:vue父子组件传值

          本文链接:https://www.haomeiwen.com/subject/wvstgktx.html