1 自定義全局組件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue自定義全局組件</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<!--1自定義組件data要有返回值,自定義組件必須返回template-->
<!--2可以在vue中使用自定義組件-->
<!--3全局自定義組件可以多次使用-->
<!--4自定義組件可以使用多次,函數內部數據是局部變量,不會相互影響(若要影響,聲明全局變量)-->
<div id="app">
<buttion-counter></buttion-counter>
<buttion-counter></buttion-counter>
</div>
</body>
<script type="text/javascript">
var myData = {count:0};
//自定義組件buttion-counter(全局組件),它支持Vue的data,methode,鉤子函數等.必須在創建前定義.
Vue.component("buttion-counter",{
data:function(){
/* return {
//局部變量
count:0
} */
//全局變量
return myData;
},
//自定義組件 返回的標籤與內容.只能返回一個根元素
template:'<buttion v-on:click="count++">{{count}}</buttion>'
})
new Vue({
el:"#app"
});
</script>
</html>
2 自定義局部組件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue自定義局部組件</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script type="text/template" id='temp'>
<div>
{{massage}}
<ul>
<li>第一部分</li>
<li>第二部分</li>
</ul>
</div>
</script>
</head>
<body>
<!--全局組件-->
<div id="app">
<my_header></my_header>
</div>
<!--局部組件-->
<div id="app1">
<my_header>
<button slot="left">left</button>
<button slot="right">right</button>
</my_header>
</div>
</body>
<script type="text/javascript">
Vue.component("my_header",{
//自定義組件 返回的標籤與內容.只能返回一個根元素
template:'<div>全局組件</div>'
});
new Vue({
el:'#app'
});
new Vue({
el:'#app1',
//局部組件優先,且只對當前有效
components:{
'my_header':{
template:'<div><slot name="left"/>全局組件<slot name="right"/></div>',
//javascript中定義
/* template:'#temp',
data:function(){
return{
massage:'這是一個局部組件'
}
} */
}
}
})
</script>
</html>
參考
官網地址: https://cn.vuejs.org/
Ant Design of Vue地址: https://vue.ant.design/docs/vue/introduce-cn/