Reputation: 21
I want to pass a property that doesn't have any value - only name. I want the name to be dynamic according the prop.
I want to create a component of tool-tip that get the tool-tip side -> top left right or bottom. in v-tooltip there isn't property side, all side is another property without value. I want it to change according the prop (side is a variable - a prop of my component).
<template>
<v-tooltip side>
<template slot="activator">
<slot slot="activator"></slot>
</template>
<span>{{text}}</span>
</v-tooltip>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true,
},
side: {
default: 'top',
},
},
}
</script>
I can't find a way to use prop as the name of the property
Upvotes: 2
Views: 2116
Reputation: 20745
There are two things that you need to realise. In Vue, calling a component with <my-component has-this-prop />
it the same as calling a component with <my-component :has-this-prop="true" />
. The boolean basically toggles the prop.
You can also dynamically change which props are bound to a component by using the v-bind
syntax without a prop name, as outlined in the documentation.
This means that if you have a prop called side
in your parent component that always contains the correct side, you can create a computed property that contains all the props you want to pass, then use v-bind
on your v-tooltip
to pass the props:
<template>
<v-tooltip v-bind="tooltipProps">
<!-- Something -->
</v-tooltip>
</template>
<script>
const validSides = [
'top',
'top left',
'top center',
'top right',
// you get the idea
];
export default {
props: {
side: {
type: String,
default: 'top',
validator(prop) {
return validSides.contains(prop);
}
}
},
computed: {
tooltipProps() {
if (!validSides.contains(this.side)) {
return {};
}
const propsNames = this.side.split(' ');
const props = {};
for (const propName of propsNames) {
props[propName] = true;
}
return props;
}
}
}
</script>
Upvotes: 4