Home > OS >  reference a prop type string inside a string - vue js
reference a prop type string inside a string - vue js

Time:07-06

How do you do this?

I need to use a prop in a string, and I thought you did that with ${} but idk.

<MyComponent valueId="12345678" />

MyComponent.vue:

<template>
    <div>
        <iframe src="https://app.com/apikey=12345qwerty&valueid=${valueId}" frameborder="0"></iframe>
    </div>
</template>

Vuejs component props as string

this isn't quite it because this user is asking how to pass a prop as a string....not reference a prop in a string

I also tried

<template>
    <div>
        <iframe src="https://app.com/apikey=12345qwerty&valueid=[valueId]" frameborder="0"></iframe>
    </div>
</template>

So when I google reference a prop type string inside a string vue site stackoverflow.com these are the results

With React prop-types is it possible to validate on whether a string contains something?

Other ways of showing prop-based conditonal text in Vue?

Invalid Prop for Model Name, String Input presented as 'Undefined'

sadly none of these answer my question.

How do you put a prop dynamically into a string?

ok i just tried

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

<template>
    <div>
        <iframe src=`https://app.com/apikey=12345qwerty&valueid=${valueId}` frameborder="0"></iframe>
    </div>
</template>

3:21 error Parsing error: unexpected-character-in-unquoted-attribute-value vue/no-parsing-error 3:76 error Parsing error: unexpected-character-in-unquoted-attribute-value vue/no-parsing-error 3:116 error Parsing error: unexpected-character-in-unquoted-attribute-value vue/no-parsing-error 3:129 error Parsing error: unexpected-character-in-unquoted-attribute-value vue/no-parsing-error 3:130 error Parsing error: unexpected-character-in-unquoted-attribute-value vue/no-parsing-error

✖ 5 problems (5 errors, 0 warnings)

CodePudding user response:

If you want a dynamic attribute, you need to insert a : before the attribute like :src, Also you can use template string `` to concatenate the valueId with the URL

<template>
<div>
    <iframe :src="`https://app.com/apikey=12345qwerty&valueid=${valueId}`" frameborder="0"></iframe>
</div>
</template>

CodePudding user response:

As you are doing String interpolation in the value of iframe src attribute, You have to delimited the whole value with backtick () characters. Please read this official documentation of [Template literals`]2.

Without template literals, when you want to combine output from expressions with strings, you'd concatenate them using the " " (plus sign).

Hence, few suggestions as per your current code :

  • If valueId will contains dynamic data. Then, pass it like :valueId.

  • iframe src attribute value should be

    <iframe :src="`https://app.com/apikey=12345qwerty&valueid=${valueId}`"></iframe>
    
  • Related