3
<template>
<label>Firstname: </label><input type="text" v-model="user.firstName">
    <br/>
    <label>Lastname: </label><input type="text" v-model="user.lastName">
    <h3>{{fullName}}</h3>
</template>

<script>
export default {
    name: 'homepage',
    data() {
      return {
        title: 'Hello',
        user: {
          firstName: 'name',
          lastName: 'surname',
        },
        showName: false,
        items: [
          {
            title: 'Item one',
          },
          {
            title: 'Item two',
          },
          {
            title: 'Item three',
          },
        ],
      };
    },
    computed: {
      fullName() {
        return this.user.firstName + ' ' + this.user.lastName;
      },
    },
  };
</script>

I am trying to return a string value in fullName() function but when I add + ' ' + ...., I get Unexpected string concatenation(prefer-template) error. If I just return this.user.firstName; it works. How can I return this.user.firstName + ' ' + this.user.lastName;?

Michael Hancock
  • 2,673
  • 1
  • 18
  • 37
Eniss
  • 975
  • 2
  • 20
  • 40
  • 5
    This is not an error with Javascript, FYI. [This has to do with linting](https://eslint.org/docs/rules/prefer-template). –  Oct 02 '17 at 21:25

1 Answers1

12

This is a lint error. There is nothing inherently wrong from a JavaScript perspective with this.user.firstName + ' ' + this.user.lastName;. However your linter is setup to show an error when it finds string concatenation. Simply use a template string instead, as it is now the preferred method.

`${this.user.firstName} ${this.user.lastName}`

If you would prefer to use concatenation. Lookup how to modify your linters rule, for example here is how to do it for eslint (which I believe you are using).

Michael Hancock
  • 2,673
  • 1
  • 18
  • 37
  • 1
    Why is this now the preferred method? – James L. Oct 19 '17 at 00:01
  • 3
    There are a number of reasons, some subjective others more objective. Some people simply prefer the way they look, making code to them more readable. Template literals have multi line and white space support built in. Some people claim they are more performant, which is true in [some cases](https://jsperf.com/template-literal-vs-string-plus/7). A more in-depth discussion can be [found here](https://stackoverflow.com/questions/27565056/es6-template-literals-vs-concatenated-strings) – Michael Hancock Oct 19 '17 at 06:10