Vue组件的data为什么是一个函数

在学习Vue中做一个小笔记。使用Vue创建一个组件的时候,这个组件有局部的数据,但是与Vue实例的data不一样的是,组件中的数据data是一个函数。其原因是组件可能会被多次使用用,如果data是一个属性值就会造成多个该组件的data都是一样的,为了实现同一种组件的数据分离,所以组件中的data是一个函数,这个函数的目的是返回一个单独的数据对象。

talk is cheap, show me the code!

<html>
<head>
<title> hello Vue</title>

<meta charset="utf-8" />
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

</head>

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

</body>

<template id="cal">
    <div>
        {{counter}}
        <button @click="increament">+</button>
        <button @click="decreament">-</button>
    </div>
</template>

<script>


Vue.component('counter', {
  template: '#cal',
  // 组件中的data必须是一个方法,因为组件可能被多次使用,这时候的data必须要分离开来,使用函数来返回对象可以实现多个同种组件的数据分离!!!!   
  data(){
      return {
          counter: 0
      }
  },
  methods: {
      increament: function() {
          this.counter++;
      },
      decreament: function() {
          this.counter--;
      },
  }
});


var app = new Vue({
    el : '#app',
    data: {
   
    },
    methods: {
     
    }
})


</script>

</html>

效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值