Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: Components/templates as props

I am currently trying to learn vue and struggling with the whole component concept.

Let's say I have some components that define tabs(like browser tabs).

This component has a prop called name.

So you'd maybe use the component like so:

<tab :name="tab.display_name"></tab>

However lets say things need to be a bit more complex. Like for example, you don't just want the name to be a string, but regular HTML. Okay, so, you can use the prop in a v-html directive and use the tab component like this:

<tab :name="'<span class=\'fancy-styling\'>' + tab.display_name + '</span>'"></tab>

This one took me a while to figure out because of all the quotes. Is there a way to escape this escape hell(pun totally intended)?

How could I take it this out into its own snippet/template?

And what if we make it even more complex - say we require the prop be a vue component?

<tab :name="'<my-custom-component @click="onClick()">' + tab.display_name + '</my-custom-component>'"></tab>

The last one is invalid on a number of levels, not the least of which being the mess of quotes.

How would I accomplish this? What is the best approach?

like image 951
martixy Avatar asked Apr 12 '18 19:04

martixy


People also ask

How do you use props in Vue component?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.

What is Vue component template?

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance's data. All Vue templates are syntactically valid HTML that can be parsed by spec-compliant browsers and HTML parsers.

Are Vue props required by default?

All props are optional by default, unless required: true is specified. An absent optional prop other than Boolean will have undefined value. The Boolean absent props will be cast to false .


1 Answers

If you are trying to inject html in props, you should really be looking at using slots.

https://vuejs.org/v2/guide/components-slots.html

like image 194
Zom Avatar answered Oct 01 '22 11:10

Zom