(1)全局注冊
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component>
</my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注冊
Vue.component('my-component', { //DOM結構必須被元素包含
template: '<div>組件內容</div>' }) new Vue({ el: "#app" }) </script>
</body>
</html>
(2)局部注冊
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component>
</my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
var Child = { template: '<div>組件內容</div>' } new Vue({ el: "#app", components: { 'my-component': Child } }) </script>
</body>
</html>
(3)is掛載組件
table、ul、ol、select這些標簽會限制其內的元素,這時可以使用is來掛載組件
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<table>
<tbody is='my-component'>
</tbody>
</table>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注冊
Vue.component('my-component', { //DOM結構必須被元素包含
template: '<div>組件內容</div>' }) new Vue({ el: "#app" }) </script>
</body>
</html>
(4)組件也可以有data,method,computed等屬性。但是data是函數,數據需要return出去。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注冊
Vue.component('my-component', { //DOM結構必須被元素包含
template: '<div>{{message}}</div>', data: function() { return { message: '組件內容' } } }) new Vue({ el: "#app" }) </script>
</body>
</html>
(5)解決多個組件之間數據共享問題
給組件返回一個新的data對象
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注冊
Vue.component('my-component', { //DOM結構必須被元素包含
template: '<button @click="counter++">{{counter}}</button>', data: function() { return { counter: 0 } } }) new Vue({ el: "#app" }) </script>
</body>
</html>
(6)props傳遞數據、events觸發事件和slot內容分發構成Vue組件的3個API來源。