mmbrian
mmbrian

Reputation: 1662

Vue: How to use prop value inside component template

I am using a generic file selector component from https://alligator.io/vuejs/file-select-component/ and now I want to be able to pass "accept" value also from outside. In other words, I wanna be able to do something like

<file-select :accept="application/json,.json"></file-select>

which should translate to

<input type="file" accept="application/json,.json"/>

But so far my attempts at binding the value of this prop to file input's accept attribute have all failed (e.g. using {{ accept }} or this.accept). I was wondering if I can directly use prop value inside my component's template. any ideas would be greatly appreciated!

Upvotes: 0

Views: 1748

Answers (2)

Leite
Leite

Reputation: 994

You can extend their component to add the accept property, but given it's such a small component, you might be better changing the code provided in the tutorial to add the prop.

Vue adds any non-prop attribute to the root element, so when you do <file-select :accept="application/json,.json"></file-select>, the label is getting that accept added as an attribute, if the input was the root, then that would work as you need.

To learn how to extend components, there's another alligator.io tutorial on component composition that should help you understand how to achieve this in Vue. However, since the template isn't ready for this new prop, you'd need to fully override the html.

As mentioned, you can just use their example code to create your own component that takes in an accept prop and uses it in the correct place. Extending might be more trouble than what is worth, still, good information to have.

Upvotes: 2

Julian Paolo Dayag
Julian Paolo Dayag

Reputation: 3739

You can access the native element of the FileSelect component and manually assign the accept attribute to it.

template:

<file-select ref="fileSelect"></file-select>

js:

mounted() {
    this.$refs.fileSelect.$el.accept = "application/json,.json";
}

Upvotes: 0

Related Questions