list_by_vue.html 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>动态列表</title>
  6. <style>
  7. * {
  8. margin: 0;
  9. padding: 0;
  10. }
  11. body {
  12. background-color: #000;
  13. color: #fff;
  14. }
  15. #app {
  16. width: 40%;
  17. margin: 20px auto;
  18. }
  19. #fruits>li {
  20. width: 90%;
  21. height: 50px;
  22. background-color: #6ca;
  23. margin: 4px 0;
  24. text-align: center;
  25. font-size: 20px;
  26. list-style-type: none;
  27. line-height: 50px;
  28. }
  29. #fruits>li>a {
  30. float: right;
  31. color: #fff;
  32. text-decoration: none;
  33. margin-right: 10px;
  34. }
  35. #fruits+div {
  36. margin-top: 20px;
  37. }
  38. #fname {
  39. width: 70%;
  40. height: 40px;
  41. color: #fff;
  42. border-radius: 8px;
  43. border: none;
  44. outline: none;
  45. font-size: 20px;
  46. text-align: center;
  47. vertical-align: middle;
  48. background-color: #999;
  49. }
  50. #ok {
  51. width: 19%;
  52. height: 40px;
  53. color: #fff;
  54. background-color: #a45;
  55. border: none;
  56. outline: none;
  57. font-size: 16px;
  58. vertical-align: middle;
  59. }
  60. </style>
  61. </head>
  62. <body>
  63. <div id="app">
  64. <ul id="fruits">
  65. <li v-for="fruit in fruits">
  66. {{ fruit }}
  67. <a href="" @click.prevent="removeItem(fruit)">×</a>
  68. </li>
  69. </ul>
  70. <div>
  71. <input @keydown.enter="addItem()" type="text" id="fname" v-model="fname">
  72. <button id="ok" @click="addItem()">确定</button>
  73. </div>
  74. </div>
  75. <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
  76. <script>
  77. const app = new Vue({
  78. el: '#app',
  79. data: {
  80. fruits: ['苹果', '香蕉', '榴莲', '火龙果'],
  81. fname: ''
  82. },
  83. methods: {
  84. addItem() {
  85. if (this.fname.trim().length > 0) {
  86. this.fruits.push(this.fname.trim())
  87. }
  88. this.fname = ''
  89. },
  90. removeItem(fruit) {
  91. let index = this.fruits.indexOf(fruit)
  92. if (index >= 0) {
  93. this.fruits.splice(index, 1)
  94. }
  95. }
  96. }
  97. })
  98. </script>
  99. </body>
  100. </html>