Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue 动态组件传参 #28

Open
huangshuwei opened this issue Jun 5, 2019 · 2 comments
Open

vue 动态组件传参 #28

huangshuwei opened this issue Jun 5, 2019 · 2 comments
Labels

Comments

@huangshuwei
Copy link
Owner

huangshuwei commented Jun 5, 2019

前言

现有个场景需要使用 动态组件,但是传参问题无法很好的解决。今天尝试了一种方案还不错,特此记录下

启发
思路来自以下等价方式

<component
        :is="currentComp"
        v-bind="{name:'abc',address:'xxx'}"/>

等价于

<component
        :is="currentComp"
        :name="abc"
        :address="xxx"/>

动态组件封装

约定将所有组件的传参都通过对象的形式

// dynamic-comp.vue
<template>
    <component
        :is="currentComp"
        v-bind="propsOption"/>
</template>

<script>
    export default {
        name: "DynamicComp",
        props: {
            currentComp: {
                type: String,
                required: true
            },
            // props 以对象方式传递
            propsOption: {
                type: Object,
                required: false,
                validator:function (val) {

                    return Object.prototype.toString.apply(val) === "[object Object]"
                }
            }
        }
    }
</script>

使用

// any.vue
<template>
    <dynamic-comp
        :props-option="propsOption"
        current-comp="testComp"/>
</template>
<script>
    import dynamicComp from './dynamic-comp'

    export default {
        components: {dynamicComp},
        data() {

            return {
                propsOption: {
                    prop1: "tome",
                    prop2: 123
                }
            }
        }
    }
</script>

@huangshuwei huangshuwei added the vue label Jun 5, 2019
@huangshuwei huangshuwei changed the title 动态组件传参 vue 动态组件传参 Jun 5, 2019
@konnga
Copy link

konnga commented Jun 16, 2020

请问,如果是获取后端数据后,如何传递props给动态组件?

@huangshuwei
Copy link
Owner Author

请问,如果是获取后端数据后,如何传递props给动态组件?

这有个例子,我试了下是可以的。如果是异步条件可以考虑将动态组件的propsOption属性改为非必填
示例:
https://codesandbox.io/s/focused-cherry-8wj6l?file=/src/App.vue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants