Passing props dynamically to dynamic component in VueJS

大兔子大兔子 提交于 2019-12-17 15:14:40

问题


I've a dynamic view:

<div id="myview">
  <div :is="currentComponent"></div>
</div>

with an associated Vue instance:

new Vue ({
  data: function () {
    return {
      currentComponent: 'myComponent',
    }
  },
}).$mount('#myview');

This allows me to change my component dynamically.

In my case, I have three different components: myComponent, myComponent1, and myComponent2. And I switch between them like this:

Vue.component('myComponent', {
  template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}

Now, I'd like to pass props to myComponent1.

How can I pass these props when I change the component type to myComponent1?


回答1:


To pass props dynamically, you can add the v-bind directive to your dynamic component and pass an object containing your prop names and values:

So your dynamic component would look like this:

<component :is="currentComponent" v-bind="currentProperties"></component>

And in your Vue instance, currentProperties can change based on the current component:

data: function () {
  return {
    currentComponent: 'myComponent',
  }
},
computed: {
  currentProperties: function() {
    if (this.currentComponent === 'myComponent') {
      return { foo: 'bar' }
    }
  }
}   

So now, when the currentComponent is myComponent, it will have a foo property equal to 'bar'. And when it isn't, no properties will be passed.




回答2:


You can also do without computed property and inline the object.

<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

Shown in the docs on V-Bind - https://vuejs.org/v2/api/#v-bind




回答3:


If you have imported you code through require

var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')
and initalize the data instance as below

data: function () {
            return {
                currentView: patientDetailsEdit,
            }

you can also reference the component through the name property if you r component has it assigned

currentProperties: function() {
                if (this.currentView.name === 'Personal-Details-Edit') {
                    return { mode: 'create' }
                }
            }


来源:https://stackoverflow.com/questions/43658481/passing-props-dynamically-to-dynamic-component-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!