1

Is there a way to concatenate strings with variables in a condition, without the use of inner tags such as span or other which could have v-if.

In the following example:

data() {
    return {
        useSnippet: true,
        name: 'John',
        lastName: 'Doe'
    }
}

The markup should display the data as follow:

<div>
    bunch of text
    {{useSnippet ? 'Hello {{name}}, your last name is {{lastName}}'}}
    bunch of text
</div>

This is of course returning an error.

The desired outcome would be:

bunch of textHello John, your last name is Doebunch of text

2 Answers 2

2

Maybe like following snippet:

const app = Vue.createApp({
  data() {
    return {
      useSnippet: true,
      name: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    text() {
      return this.useSnippet ? `Hello ${this.name}, your last name is ${this.lastName}` : ''
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="demo">
  bunch of text
  {{ text }}
  bunch of text
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but this uses inner tags, span, in this case, as mentioned in the question, I really want to avoid tags.
This works, but was more looking for inline, like answer provided below. Thanks!
You are welcome mate, btw you should avoid logic in template.
1

As you are using the turnery operator the syntax goes like this

condition? : but you have not used : so that is why I guess it is giving you an error

so you can do something like this bunch of text {{useSnippet ? Hello ${name}, your last name is ${lastName} : ''}} bunch of text

4 Comments

No, this will not fix it, I had used this as well before, :null
please check updated answer
Strange, I had used string literals before, and returned error, so stepped away from that. But this is the approach I was after. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.