1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>vue</title> 6 <style> 7 .active { 8 color:red 9 } 10 </style> 11 </head> 12 <body> 13 <div id="app"> 14 <table> 15 <tbody> 16 <tr is="row"></tr> 17 <tr is="row"></tr> 18 <tr is="row"></tr> 19 </tbody> 20 </table> 21 </div> 22 23 24 <!-- 开发环境版本,包含了用帮助的命令行警activeOne告 --> 25 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 26 <script> 27 Vue.component('row',{ 28 template: '<tr><td>this is row</td></tr>' 29 }) 30 var app = new Vue({ 31 el: '#app' 32 }) 33 </script> 34 </body> 35 </html>
注意:table 里面只能写tr>td, 使用is=row,若直接使用<row></row>则template模板不在table里面。其它select ,ul, ol等都是用is
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>vue</title> <style> .active { color:red } </style> </head> <body> <div id="app"> <table> <tbody> <tr is="row"></tr> <tr is="row"></tr> <tr is="row"></tr> </tbody> </table> </div> <!-- 开发环境版本,包含了用帮助的命令行警activeOne告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> Vue.component('row',{ data: function() {//子组件里的data是function而不是object, 且使用return return { content: 'this is row' } }, template: '<tr><td>{{content}}</td></tr>' }) var app = new Vue({ el: '#app' }) </script> </body> </html>
/子组件里的data是function而不是object, 且使用return
让每一个子组件都拥有一个独立的数据存储,不会出现多个子组件之间互相影响的情况
ref
vue一般不操作dom节点,但如果要操作的话可以用ref
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>vue</title> 6 <style> 7 .active { 8 color:red 9 } 10 </style> 11 </head> 12 <body> 13 <div id="app"> 14 <div ref="hello" @click="handleDivClick">Hello World</div> 15 </div> 16 17 <!-- 开发环境版本,包含了用帮助的命令行警activeOne告 --> 18 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 19 <script> 20 21 var app = new Vue({ 22 el: '#app', 23 methods: { 24 handleDivClick: function() { 25 console.log(this.$refs.hello); 26 console.log(this.$refs.hello.innerHTML); 27 } 28 } 29 }) 30 </script> 31 </body> 32 </html>
用ref实现的子组件相加得到父组件的total值
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>vue</title> 6 <style> 7 .active { 8 color:red 9 } 10 </style> 11 </head> 12 <body> 13 <div id="app"> 14 <counter ref="one" @change="handleChange"></counter> 15 <counter ref="two" @change="handleChange"></counter> 16 <div>{{total}}</div> 17 </div> 18 19 <!-- 开发环境版本,包含了用帮助的命令行警activeOne告 --> 20 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 21 <script> 22 Vue.component('counter' , { 23 data: function() { 24 return { 25 num: 0 26 } 27 }, 28 template: '<div @click="handleDivClick">{{num}}</div>', 29 methods: { 30 handleDivClick: function() { 31 this.num++; 32 this.$emit('change'); 33 } 34 } 35 }) 36 var app = new Vue({ 37 el: '#app', 38 data: { 39 total:0 40 }, 41 methods: { 42 handleChange: function() { 43 console.log(this.$refs.one); 44 console.log(this.$refs.two); 45 return this.total = this.$refs.one.num + this.$refs.two.num; 46 } 47 } 48 49 }) 50 </script> 51 </body> 52 </html>