<!DOCTYPE HTML> <html> <head> <title>vue.js hello world</title> <script src="../vue.js"></script> </head> <body> <div id="example"> <my-component v-on:click="cao"></my-component> </div> <script> // 定義 var MyComponent = Vue.extend({ template: '<div>A custom component!</div>' }); // 注冊 Vue.component('my-component', MyComponent); // 創建根實例 new Vue({ el: '#example', methods:{ cao:function(event){ alert(event.target.tagName); } } }); </script> </body> </html>
效果:
局部注冊
不需要全局注冊每個組件。可以讓組件只能用在其它組件內,用實例選項 components
注冊:
var Child = Vue.extend({ /* ... */ }) var Parent = Vue.extend({ template: '...', components: { // <my-component> 只能用在父組件模板內 'my-component': Child } })