不知道如何在VueJS中基于模板添加元素

问题描述 投票:0回答:1

我正在尝试使用 Vue 来更新我的静态 HTML。我需要的是更新一些元素(例如,更改内部 HTML、图标或其中的某些部分),并向 DOM 添加一个新元素。我的要求是使用模板来添加新元素,因为使用 JS 动态创建很乏味,因为它们可能很复杂。

这是我更新元素“counter”的代码:

<!DOCTYPE html>
<html>
<head>
  <title>Counter</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
  <div class="list">
     <div class="counter" id="a">5</div>
  </div>
 <button>update</update>

  <script>
    new Vue({
      el: '#a',
      data: {
        counter: 5
      },
      mounted() {
        this.counter = 10;
      },
      template: '<div>{{ counter }}</div>'
    });
  </script>
</body>
</html>
  1. 如何将其更改为添加新的“计数器”元素到“列表”?
  2. 如何更改它以通过单击按钮更新现有计数器而不完全重写它?
vue.js
1个回答
0
投票

与 Vue 3 一样,您可以将应用程序安装到 Vue 模板中,如下所示:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.8/vue.global.min.js"></script>
<div class="list" id="app">
   <div class="counter"> {{ counter }}</div>
   <button @click="counter++">update</update>
</div>

<script>
     Vue.createApp({
      data: () => ({
        counter: 5
      }),
      mounted() {
        this.counter = 10;
      },
    }).mount('#app');
</script>

© www.soinside.com 2019 - 2024. All rights reserved.