vue父组件向子组件传递数据的注意事项

时间:2019-11-11
本文章向大家介绍vue父组件向子组件传递数据的注意事项,主要包括vue父组件向子组件传递数据的注意事项使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

注意事项:

如果父组件的数据是通过异步请求获取的数据,那么子组件接收的时候尽量对子组件加一个v-if="data",来判断一下data是否存在,也就是数据是否请求成功。

如果不加判断的话,可能会出现属性报错的问题。比如:

//Parent.vue
<template>
    <div class="box">
        <Child :info="info" />
    </div>
</template>

<script>
import Child from './Child'
export default {
    name: 'Parent',
    components: {
        Child,
    },
    data() {
        return {
            info: {}, //这里如果子组件用到了 userInfo,但是请求未返回之前这个属性里面并没有userInfo,可以会出现 info.userInfo.name这个name获取时报错。当然出可以写默认值
        }
    },
    created() {
        setTimeout(() => {
            this.info = {
                userInfo: {
                    name: 'hello world',
                },
                address: 'xxx, xxx, xxx',
            }
        }, 1000)
    },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
h3 {
    margin: 40px 0 0;
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    display: inline-block;
    margin: 0 10px;
}
.green {
    color: #42b983;
}
.box {
    text-align: left;
    width: 600px;
    margin: 0 auto;
}
input {
    width: 200px;
    height: 35px;
    line-height: 35px;
}
</style>

原文地址:https://www.cnblogs.com/hellolol/p/11833406.html