vue组件中data为什么需要用函数

组件中用函数的原因

如果不用函数返回就会出现连锁反应。

  • 因为组件会被多次复用,所以每次用的时候用函数返回一个data,那么每次的data都不会相互影响。
  • 每一个组件的实例对象都有一个自己的对象。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
    {{message}}
  <cpn></cpn>
</div>
<template id="cpn">
  <div>
    <h2>当前计数为:{{count}}</h2>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </div>
</template>
<script src="../vue.js"></script>
<script>
  Vue.component('cpn',{
    template:'#cpn',
    // 函数返回的时候是一个内存地址
    data() {
      return {
        count: 0
      }
    },
    methods: {
      increment() {
        this.count ++
      },
      decrement() {
        this.count --
      }
    }
  })
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
    }
  })
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/ch2020/p/14842462.html