Vue.js的組件就是提高重用性的,讓代碼可復(fù)用。組件與Vue的示例類似,需要注冊后才可以使用。注冊有全局注冊和局部注冊兩種方式。全局注冊后, 任何 Vue 實例都可以使用
在 Vue 中,一個組件本質(zhì)上是一個被預(yù)先定義選項的 Vue 實例
還是直接上代碼,詳解在注釋中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 全局子組件 -->
<my-component></my-component>
<hr>
<!-- 局部子組件 -->
<jb-component></jb-component>
<hr>
<!-- Vue 組件的模板在某些情況下會受到 HTML 的限制,比如<table>內(nèi)規(guī)定只允許是〈<tr>、<td> <th>等這些表格元素,所以在<table>內(nèi)直接使用組件是無效的。
這種情況下,可以使用特殊的 is 屬性來掛載組件, 示例代碼如下:
-->
<!-- tbody 在渲染時, 會被替換為組件的內(nèi)容。常見的限制元素還有<ul>、<ol>、<select> -->
<table>
<tr is="my-component"></tr>
</table>
<hr>
<!-- 帶有data函數(shù)的全局子組件 -->
<my-component1></my-component1>
<hr>
<!-- 父組件傳遞固定數(shù)據(jù)給子組件 -->
<my-component2 name='zhangsan'></my-component2>
<!-- 父組件傳遞動態(tài)數(shù)據(jù)給子組件 -->
<!-- 由于 HTML 特性不區(qū)分大小寫,當(dāng)使用 DOM 模板時,駝峰命名 CamelCase)的 props 名稱要轉(zhuǎn)為短橫線分隔命名 -->
<my-component2 :user-id='userId'></my-component2>
</div>
<script>
//全局注冊組件的方式,放到初始化Vue之前
Vue.component('my-component', {
//放組件內(nèi)容
//template的 DOM 結(jié)構(gòu)必須被一個元素包含,如果直接寫成 “這里是組件的內(nèi)容”, 不帶 “<div></div>”是無法渲染的
template: '<div>這是全局組件內(nèi)容</div>'
})
//全局子組件除了 template 選項外,組件中還可以像 Vue 實例那樣使用其他的選項,比如 data、 computed、 methods 等。但是在使用 data 時, 和實例稍有區(qū)別,
//data 必須是函數(shù),然后將數(shù)據(jù) return 出去,
Vue.component('my-component1',{
data() {
return {
count:0
}
},
template:'<button @click="count++"> You clicked me {{ count }} times. </button>'
})
// 接收父組件傳遞數(shù)據(jù)的全局子組件
Vue.component('my-component2',{
// props用來接收來自父組件傳遞過來的數(shù)據(jù)
props:['name','userId'],
//子控件的template中只能有一個根標(biāo)簽
template:'<div><div> {{ name }} </div> <div> {{ userId }} </div></div> '
})
//局部組件注冊需要采用components
var Child = {
template: "<div>局部自定義組件</div>"
}
new Vue({
el: "#app",
components: {
'jb-component': Child
},
data:{
age:12,
userId:1
}
})
</script>
</body>
</html>