Official website link: https://cn.vuejs.org/v2/guide/components.html
Reference link: http://www.cnblogs.com/keepfool/p/5625583.html
Teaching video reference link:
Most of the options passed in to the Vue constructor can also be used in Vue.extend() or Vue.component().
Vue.js specifies that when defining data options, you must use the function
If the data option points to an object, this means that all component instances share a single data. The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> <body> <div id="app"> <my-com1></my-com1> <my-com1></my-com1> <my-com1></my-com1> <my-com1></my-com1> </div> <div id="app1"></div> <script> let data={ count:0 } Vue.component('myCom1',{ template:"<h3 @click='count++'>This is the component~{{count}}</h3>", data:function(){ return data } }); var vm=new Vue({ el:'#app' }) new Vue({ el:'#app1', template:'<my-com1></my-com1>' }) </script> </body> </body> </html>
The operation results are as follows:
Click any component, the data of other components will change.
Therefore, we should use a function as the data option to return a new object:
Vue.component('my-component', { data: function(){ return {a : 1} } })
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> <body> <div id="app"> <my-com1></my-com1> <my-com1></my-com1> <my-com1></my-com1> <my-com1></my-com1> </div> <div id="app1"></div> <script> let data={ count:0 } Vue.component('myCom1',{ template:"<h3 @click='count++'>This is the component~{{count}}</h3>", data:function(){ return { count:0 } } }); var vm=new Vue({ el:'#app' }) new Vue({ el:'#app1', template:'<my-com1></my-com1>' }) </script> </body> </body> </html>
The operation results are as follows:
The data between components does not affect each other.