1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="../node_modules/vue/dist/vue.min.js"></script> 7 </head> 8 <body> 9 <div id="app"> 10 <flash diycontent="Qapple">父组件指的是这里</flash> 11 </div> 12 <script> 13 var tpl1={ 14 props:[‘diycontent‘], 15 template:‘<li>这里是组件{{diycontent}}</li>‘//子组件指的是这里 16 } 17 Vue.component("flash",tpl1) 18 new Vue({ 19 el:"#app" 20 }) 21 </script> 22 </body> 23 </html>
1、首先要搞清楚子组件跟父组件分别指的是谁,如代码里展示的:父组件是flash,子组件是template
2、父向子传递数据,用属性props
3、子向父传递数据,用事件this.$emit
4、一个组件,相当于一个Vue实例
5、组件的名称要注意驼峰式问题
6、组件的数据data要用函数模式
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="../node_modules/vue/dist/vue.min.js"></script> 7 </head> 8 <body> 9 <div id="message-event-example" class="demo"> 10 <p v-for="msg in messages">{{ msg }}</p> 11 <button-message v-on:message="handleMessage"></button-message> 12 </div> 13 <script> 14 Vue.component(‘button-message‘, { 15 template: `<div> 16 <input type="text" v-model="message" /> 17 <button v-on:click="handleSendMessage">Send</button> 18 </div>`, 19 data: function () { 20 return { 21 message: ‘test message‘ 22 } 23 }, 24 methods: { 25 handleSendMessage: function () { 26 this.$emit(‘message‘, { message: this.message }) 27 } 28 } 29 }) 30 31 new Vue({ 32 el: ‘#message-event-example‘, 33 data: { 34 messages: [] 35 }, 36 methods: { 37 handleMessage: function (payload) { 38 this.messages.push(payload.message) 39 } 40 } 41 }) 42 </script> 43 </body> 44 </html>