Dream4ever / Knowledge-Base

record every requirement and solution here
https://www.hewei.in/
36 stars 6 forks source link

Vue.js 动态加载组件并动态传参 #188

Closed Dream4ever closed 2 years ago

Dream4ever commented 2 years ago

解决方案

官方文档 Dynamic & Async Components 提供了动态加载组件的方案,用下面的代码即可实现:

<component :is="currentComponent"></component>
data() {
  return {
    currentComponent: 1 ? 'VideoContainer' : 'AudioContainer',
  };
},

动态传参的方案通过 Google pass object to dynamic component props 关键字找到了解决方案:Passing props dynamically to dynamic component in VueJS。经过测试并修改错误,最终解决方案如下:

<component :is="currentComponent" :compProps="compProps"></component>
data() {
  return {
    currentComponent: 1 ? 'VideoContainer' : 'AudioContainer',
  };
},
computed: {
  compProps() {
    return 1 ? 'VideoProps' : 'AudioProps';
  },
},