ES6意外的字符串连接

Eni*_*iss 2 string-concatenation eslint vue.js

<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>
Run Code Online (Sandbox Code Playgroud)

我试图在fullName()函数中返回一个字符串值但是当我添加时+ ' ' + ....,我得到意外的字符串连接(prefer-template)错误.如果我回来this.user.firstName;就行了.我怎么回来this.user.firstName + ' ' + this.user.lastName;

Mic*_*ock 7

这是一个棉绒错误.从JavaScript的角度来看,没有任何内在错误this.user.firstName + ' ' + this.user.lastName;.但是,您的linter设置为在找到字符串连接时显示错误.只需使用模板字符串,因为它现在是首选方法.

`${this.user.firstName} ${this.user.lastName}`
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢使用串联.查找如何修改你的linters规则,例如这里是如何为eslint(我相信你正在使用).

  • 有许多原因,一些主观的其他更客观.有些人更喜欢他们的外观,使代码更具可读性.模板文字内置了多行和空格支持.有些人声称它们性能更高,在某些情况下(https://jsperf.com/template-literal-vs-string-plus/7)也是如此.可以[在此处找到]进行更深入的讨论(/sf/ask/1929553951/) (2认同)