【问题标题】:How to render Vue Component dynamically with render()如何使用 render() 动态渲染 Vue 组件
【发布时间】:2021-09-15 18:16:14
【问题描述】:

Vuejs 3中,我想使用render() 函数创建一个VNode,并传递给它一个Vue Component。该组件因当前路线而异。

vite.js 中,我还没有找到在我的ViewComponent 计算函数中动态导入组件的方法。

使用 webpack,我通常可以使用 return require(`./pages/${matchingPage}.vue`).default,但使用 vitejs 则无法做到这一点,因为我会收到 Require is not a function 错误。

所以我尝试了return import(`./pages/${matchingPage}.vue`),但它返回的是Promise,而不是Component

//main.js

import {createApp, h} from 'vue'
import routes from './routes'

const SimpleRouterApp = {
  data: () => ({
    currentRoute: window.location.pathname
  }),

  computed: {
    ViewComponent () {
      const matchingPage = routes[this.currentRoute] || '404'
      return import(`./pages/${matchingPage}.vue`)
    }
  },

  render () {
    return h(this.ViewComponent)
  },

  created () {
    window.addEventListener('popstate', () => {
      this.currentRoute = window.location.pathname
    })
  }
}

createApp(SimpleRouterApp).mount('#app')

我可以尝试哪些其他方法使render() 可以动态返回Component

【问题讨论】:

    标签: javascript vue.js vuejs3 vite


    【解决方案1】:

    你可以使用async-components

    import {createApp, h,defineAsyncComponent} from 'vue'
    ....
      
    
      render () {
      const matchingPage = routes[this.currentRoute] || '404'
        const ViewComponent= defineAsyncComponent(
          () =>import(`./pages/${matchingPage}.vue`)
       
       )
        return h(ViewComponent)
      },
    

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 1970-01-01
      • 2019-10-20
      • 2022-08-15
      • 2017-03-17
      • 2019-06-09
      • 2021-02-08
      • 2019-05-31
      • 2020-05-22
      相关资源
      最近更新 更多