image.png

{{ }} 显示值

用于在template属性中显示值其他属性定义的变量的值、函数返回的值、表达式的值

1、基本

数据绑定最常见的形式就是使用“Mustache”语法 (双大括号) 的文本插值:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <div id="app"></div>
  11. <template id="my-app">
  12. <!-- 这里会显示为:Hello World -->
  13. <h2>{{message}}</h2>
  14. <!-- 相当于<h2>Hello World</h2> -->
  15. </template>
  16. <script src="https://unpkg.com/vue@next"></script>
  17. <script>
  18. const App = {
  19. template: '#my-app',
  20. data() {
  21. return {
  22. message: "Hello World",
  23. counter: 100,
  24. isShow: true
  25. }
  26. },
  27. methods: {
  28. getReverseMessage() {
  29. return this.message.split(" ").reverse().join(" ");
  30. },
  31. toggle() {
  32. this.isShow = !this.isShow;
  33. }
  34. }
  35. }
  36. Vue.createApp(App).mount('#app');
  37. </script>
  38. </body>
  39. </html>

Mustache 标签将会被替代为对应数据对象上 message变量 的值。无论何时,绑定的数据对象上 message变量 发生了改变,插值处的内容都会更新。

2、计算表达式

  1. <template id="my-app">
  2. <h2>{{counter * 10}}</h2>
  3. <h2>{{ message.split(" ").reverse().join(" ") }}</h2>
  4. </template>

如果计算方式比较复杂,就不建议直接放这里,应该用计算属性
https://www.yuque.com/yejielin/mypn47/bilegi#EF7y8

3、显示函数返回值

  1. <template id="my-app">
  2. <h2>{{getReverseMessage()}}</h2>
  3. </template>
  4. ...
  5. <script src="../js/vue.js"></script>
  6. <script>
  7. const App = {
  8. template: '#my-app',
  9. data() {
  10. return {
  11. message: "Hello World",
  12. counter: 100,
  13. isShow: true
  14. }
  15. },
  16. methods: {
  17. getReverseMessage() {
  18. return this.message.split(" ").reverse().join(" ");
  19. },
  20. toggle() {
  21. this.isShow = !this.isShow;
  22. }
  23. }
  24. }
  25. Vue.createApp(App).mount('#app');
  26. </script>

4、显示三元运算符的值

  1. <template id="my-app">
  2. <!-- 4.三元运算符 -->
  3. <h2>{{ isShow ? "哈哈哈": "" }}</h2>
  4. </template>

其他

语句、流程控制等不会生效