当前位置:   article > 正文

ES6——模板字符串_vue es6的模板字符串

vue es6的模板字符串

与普通字符串的区别

相较于普通字符串,模板字符串使用反引号 ` 来代替普通字符串中的用双引号 " 和单引号 ’ ,模板字符串省去了大量 + 和 " 的使用,方便阅读和编写

  <script>
    const name = "张三";
    const age = "18";
    const sex = "男";

    const normal = "他叫" + name + ",是一名" + age + "岁的" + sex + "人";
    const template = `他叫${name},是一名${age}岁的${sex}`;
    document.getElementById("normal").innerText = normal;
    document.getElementById("template").innerText = template;
  </script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这里插入图片描述


模板字符串支持多行编写

    const normal = 
      "名字:" + name + 
      "年龄:" + age + 
      "性别:" + sex;
    const template = `
      名字: ${name}
      年龄: ${age}
      性别: ${sex}
    `
    document.getElementById("normal").innerText = normal;
    document.getElementById("template").innerText = template;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

输出结果:
在这里插入图片描述


模板字符串内也可以正常使用函数以及表达式

    const name = "张三";
    const age = "18";
    const sex = "男";
    function fn(name) {
      return name + "成年了吗?";
    }
    const template = `
      ${fn(name)}
      ${age >= 18 ? "成年了" : "没成年"}
    `;
    document.getElementById("template").innerText = template;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/93088
推荐阅读
相关标签
  

闽ICP备14008679号