【问题标题】:Vue3 how send props to created child componentVue3如何将道具发送到创建的子组件
【发布时间】:2021-01-20 12:03:41
【问题描述】:

props 被初始化,但是在.mount 之后它们消失了。我应该如何正确设置 props 与动态加载的组件?

import {createApp} from 'vue'

blockView = createApp(Block);
blockView.props = {
    type: json['type'],
    title: json['title'],
    subtitle: json['subtitle']
}
blockView.mount(this.$refs.container)

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    Props 不适用于应用程序,只有组件,但是我发现这些可以将值传递给应用程序。

    1。使用注入/提供

    const app = Vue.createApp({
        inject: ['name'],
        // ...etc
    })
    app.provide("name", "Ludwig")
    app.mount('#app2')
    

    这不完全是一个道具(需要在挂载之前传递),但可以为你工作。

    更多信息:https://v3.vuejs.org/api/application-api.html#provide

    2。嵌套作为渲染函数并包装

    通过包装在渲染函数中,您可以传递道具。如果您再次将其包装在自定义挂载函数中,则可以自定义以允许传递道具。

    // the app as a component
    const appComponent = Vue.defineComponent({
      name: "appComponent",
      props: {
        name: {}
      },
      // ...etc
    })
    
    // wrap mount function
    const mountApp = (selector, props) => {
      // the actual app is just a simple render function
      const app = Vue.createApp({
        components: { appComponent },
        render() {
          return Vue.h(appComponent, props)
        }
      })
      // mount to the passed selector
      app.mount(selector);
    }
    
    // call function with props
    mountApp('#app1', {
      name: "Darla"
    });
    

    示例fiddle

    【讨论】:

    • vue3 中还有其他方法可以用 props 创建子组件吗?而不是 .createApp
    • createApp 创建一个 vue 应用。如果您有应用实例,则使用 defineComponentcomponent 创建组件
    猜你喜欢
    • 2021-03-16
    • 2020-06-02
    • 2020-12-25
    • 2021-07-29
    • 1970-01-01
    • 2022-11-23
    • 2021-06-25
    • 2016-09-15
    • 2020-07-29
    相关资源
    最近更新 更多