Skip to content
Advertisement

Vue props that aren’t explicitly declared

I am making an attempt at something similar to redux-form but in Vue & with Vuex. Basically it should make the handling of forms more streamlined and make you write less boilerplate.

The problem i’m having is when i’m trying to pass props dynamically to a component from a HOC. I’m not quite sure how to do it. In React you would simply do something like this:

<VfField unknownPropA="abc" unknownPropB="123" name="test" />

And in VfField.js:

export default ({name, ...props}) => <div name={name}><InputComponent {...props} /></div>

This would result in props being an object containing unknownPropA and unknownPropB.

But in Vue I have some code that looks like this:

<vf-form @submit="submit" @validate="validate">
  <vf-field type="text" name="username" unknownPropA="abc"></vf-field>
  <vf-field type="password" name="password" unknownPropB="123"></vf-field>
  <button type="submit">Submit</button>
</vf-form>

So how can vf-field then access these “unknown” props and pass them to their child component? $vm.$props simply yields the props i explicitly declared, but completely disregards the other(unknownPropA and unknownPropB). The power to “dynamically” pass props is what i’m looking for since it’s really useful in many cases.

Note:

So far i think Vue is great for simple things and it’s way faster to get something up and running than it would be in, say, React. But as soon as something is “out of the ordinary”, so far, i find that React is more helpful. This may, of course, be due to my lack of knowledge in Vue.

Advertisement

Answer

This is tricky and certainly not supported natively, however you can get the passed attributes from vnode using this.$vnode.elm.attributes and then loop through them and add them to a props object (which does need to be declared upfront). Because you will be processing this yourself I would put this in a mixin so it can be reused, but you can do:

  methods: {
    getProps() {
      let props = this.$vnode.elm.attributes;
      Object.keys(props).forEach(key => {
        this.$set(this.props, props[key].name, props[key].nodeValue)
      });
    }
  },
  data(){
    return{
      props: {}
    }
  }

With this you can then pass unknown props as if you declared them in your component.

I’ve made a JSFiddle to show you the process: https://jsfiddle.net/2c23Lb5t/

Here’s how you would do this with a mixin: https://jsfiddle.net/fej7wu5f/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement