vue 父子、爷孙组件传值 (provide && inject异步)

151 阅读1分钟
适用场景

  对于普通的父子传值,个人还是更推荐props

该需求为:列表页(list1)搜索框(selectForm)用到一个筛选列表(selectList),而其form表单弹窗内,点击某按钮弹出新的选择列表弹框(dialog2->list2dialog3->list3根据某type字段为不同弹框),列表可搜索同样用到了该selectList。为了不对接口进行多次请求,使用 provide && inject实现传值。

<template>
    <son></son>
</template>
<script>
    provide() {
        return {
            list: () => this.list
        };
    },
    data() {
        return { list }
    }
    mounted() {
        setTimeout(() => {
            this.list = [1, 2, 3];
        }, 5000);
    } 
</script> 
<template>
    <grandson></grandson>
</template>
<template>
    <div>
        (for nowList)
    </div>
</template>
<script>
    inject: {
        getList: {
            from: 'list', // 别名,不定义时默认为同名字段 (from: 'getList')
            default: () => () => ([]) // 默认函数空列表
        }
    },
    computed: {
        nowList({ getList }) {
            return getList();
        }
    },
</script>