Vue组件中的data必须是一个function

组件可以有自己的data,并且data必须是一个function。

在下面这个例子中,data 返回了一个在外部定义的对象。并且这个组件在页面中使用了3次,点击+1时出现了如下情况:data中的count属性影响到了所有实例。

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.css">
    <style type="text/css">
		#app{
			margin:20px;
		}
    </style>
  </head>
<body>
  <div id='app'>
    <counter></counter>
    <counter></counter>
    <counter></counter>
  </div>
  <template id="tmp1">
    <div>
      <input type="button" value="+1" @click="increment">
      <h1>{{count}}</h1>
    </div>
  </template>
</body>
<script src="../lib/vue.js"></script>
<script>
  var dataObj = {count:0}
  //这是一个计数器组件,每当点击按钮,让data中的count值加1
  Vue.component('counter',{
    template:'#tmp1',
    data:function(){
      return dataObj
    },
    methods:{
      increment(){
        this.count++
      }
    }
  })
  var vm = new Vue({
    el:'#app',
  })
</script>
</html>

而当data选项是一个函数的时候,每个实例可以维护一份被返回对象的独立的拷贝,这样各个实例中的data不会相互影响,是独立的。

  Vue.component('counter',{
    template:'#tmp1',
    data:function(){
      return {count:0}
    },
    methods:{
      increment(){
        this.count++
      }
    }
  })

发布了95 篇原创文章 · 获赞 216 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/xukongjing1/article/details/82351295