vuejs:我们能否通过动态组件模式<组件:is=“type”opts=“asyncCompOptions”>为异步组件

vuejs: can we give props to async component via dynamic component pattern <component :is="type" opts="asyncCompOptions">?

本文关键字:组件 type opts 异步 asyncCompOptions 我们 vuejs 模式 动态 is      更新时间:2023-09-26

我正在努力遵循 vuejs 应用场景动态组件 + 异步组件模式。一切正常,但仍然只有一个问题:如何访问通过传入的道具数据

<component :is="asyncComp" opts="someDataForAsyncComp">

请看现场小提琴:https://jsfiddle.net/matiascx/wjab87om/8/

这是代码:

    <div id="app">
by dynamic Component:
  <component
    v-for="item in items"
    :is="item.component"
    :opts="item.options">    <!-- can we give props data to async component here? --> 
  </component><div>

以下是 js 部分:

    Vue.component('node3', function (resolve, reject) {
  setTimeout(function () {
    resolve({
      template: '<div>I am async node3!</div>',
      created: function(){
         console.log(this.opts);  // can we access props transferred into async component via component
      }
    })
  }, 1000)
})
Vue.component('node', {
  template: '<div>must be static tpl!</div>',
  props: ['opts'],
  computed: {
    log: function() {
      return JSON.stringify(this.opts);
    }
  },
  data() {
    return {}
  },
  created: function(){
  console.log(this.opts);
  }
});
Vue.component('node2', {
  template: '<div>node2</div>',
  props: ['opts'],
  computed: {
    log: function() {
      return JSON.stringify(this.opts);
    }
  },
  data() {
    return {}
  },
  created: function(){
    console.log("dfdsfsdfa");
  }
});

new Vue({
  el: '#app',
  data() {
    return {
      newItem: {
        component: "",
        options: ""
      },
      items: [{
        component: "node",
        options: {
           type: "node",
           tpl: "<div>node: {{ opts }} {{ log }}</div>"
        }
      }, 
      {
        component: "node2",
        options: {
            type: "node2",
          tpl: "<div>node2: {{ opts }} {{ log }}</div>"
        }
      },
       {
        component: "node3",
        options: {
            type: "node3",
          tpl: "<div>node3: {{ opts }} {{ log }}</div>"
       }
      }
      ]
    };
  },
  computed: {
    isButtonDisplayed() {
      return this.newItem.component && this.newItem.options
    }
  },
  methods: {
    addItem() {
      this.items.push(this.newItem);
      this.newItem = {
        component: "",
        options: ""
      }
    }
  }
});

我在你的jsfiddle中添加了三行:

// dynamic component
var _this = this
this.$nextTick(()=>{console.log(JSON.stringify(_this.$options._parentVnode.data.attrs.opts))})
// static component
console.log(JSON.stringify(this.$options.propsData.opts))

https://jsfiddle.net/gurghet/wjab87om/11/

我不认为这是最好的方法,最好问问埃文。