vue组件data必须是函数

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>

  <body>
    <div id="app">
      <comp></comp>
      <comp></comp>
    </div>

    <template id="comp">
      <div id="">
        <p>{{message}}</p>
        <button @click="add">+</button>
        {{ count }}
        <button @click="sub">-</button>
      </div>
    </template>

    <script>
      const app = new Vue({
        el: '#app',
        data: {

        },
        components: {
          comp: {
            template: '#comp',
            // data必须是函数
            data() {
              return {
                message: 'Hello Vue.js!',
                count: 1,
              }
            },
            methods: {
              add() {
                this.count++;
              },
              sub() {
                this.count--;
              }
            }
          },
        }
      })
    </script>
  </body>
</html>

posted @ 2021-07-05 20:50  thomas_blog  阅读(29)  评论(0编辑  收藏  举报