A. L
A. L

Reputation: 12649

How to add props to component outside of template

So let's just say that I have a HelloWorld component that I would like to import multiple times and assign some props to each one (as each instance will be doing their own thing). Usually you'll do something like this:

To keep it simple I haven't used proper syntax.

  import HelloWorld from "./components/HelloWorld";

  <HelloWorld v-if="which" title="0" key="1"/>
  <HelloWorld v-else title="1"/>

However, I was wondering if there was a way to import them with props already assigned so something like:

import HelloWorld from "./components/HelloWorld";
import HelloWorld1 from "./components/HelloWorld";

HelloWorld.props = { title: "1" } // this doesn't work
HelloWorld1.props = { title: "2" } // this doesn't work

In order to use <component>

E.g.

<component :is="which"/>

which = "HelloWorld" || "HelloWorld1"

Upvotes: 0

Views: 39

Answers (1)

thanksd
thanksd

Reputation: 55644

A component's props can only be set in the component definition object.

It looks like you're attempting to pass different prop values based on the value of which. You can do that by passing an object to v-bind:

<HelloWorld v-bind="which ? { title: '0', key: '1' } : { title: '1' }"/>

Upvotes: 3

Related Questions