1,通过全局组件,向各个子组件里面创建各自需要的按钮
全局组件又叫公共组件的声明:Vue.component(a,b)
参数a是自定义全局组件的名称,参数b是options对象
(1),全局组件的dom元素里添加<slot></slot>
标签并给全局组件命名
slot作为承载分发内容的出口
Vue.component('vbtn',{
// slot作为承载分发内容的出口
template:`<button>
<slot></slot>
</button>`,
props:['type']
})
(2),给需要的子组件里面添加该全局组件,并写上需要的value值
<vbtn >播放</vbtn>
<vbtn>删除</vbtn>
2,给全局组件创建的元素写class样式
(1),先给子组件里的全局组件Dom元素添加自定义属性(下面添加的是 type=“success” )
var Vcontent={
template:`
<div class='content'>我是内容组件
<vbtn type="success" @click.native="show">播放</vbtn>
</div>
`,
methods:{
show(){
alert("hello")
}
}
};
(2),在全局组件里面用props接收子组件的自定义属性,然后全局组件就可以用该属性了
Vue.component('vbtn',{
// slot作为承载分发内容的出口
template:`<button class="all" :class="type">
<slot></slot>
</button>`,
props:['type']
})
3,通过全局组件添加的元素的事件需要用.native
来获取原生dom元素的全局属性
var Vcontent={
template:`
<div class='content'>我是内容组件
<vbtn type="success" @click.native="show">播放</vbtn>
</div>
`,
methods:{
show(){
alert("hello")
}
}
};
下面附上我的源码:
css样式:
<style>
*{
margin:0;
padding:0;
}
.head{
width: 100%;
height: 150px;
background-color: orange;
}
.main2{
width: 100%;
height: 1000px;
}
.aside{
width: 30%;
height: 100%;
float:left;
background-color: aquamarine;
}
.content{
width: 70%;
height: 100%;
float:left;
background-color: pink;
}
.all{
width: 50px;
height: 30px;
border:2px solid red;
}
.success{
background-color: blueviolet
}
</style>
DOM元素:
<div id="app"></div>
js编码:
<script>
Vue.component('vbtn',{
// slot作为承载分发内容的出口
template:`<button class="all" :class="type">
<slot></slot>
</button>`,
props:['type']
})
// 声明子组件Vcontent
var Vcontent={
template:`
<div class='content'>我是内容组件
<vbtn type="success" @click.native="show">播放</vbtn>
</div>
`,
methods:{
show(){
alert("hello")
}
}
};
// 声明子组件Vaside
var Vaside={
template:`
<div class='aside'>
我是侧边栏组件
<vbtn>删除</vbtn>
</div>
`
};
// 声明子组件Vhead
var Vhead={
template:`
<div class='head'>
我是头部组件
<vbtn>按钮</vbtn>
</div>
`,
methods: {
},
};
var App={
data(){
return{
}
},
// 使用子组件
template:`
<div class='main' >
<Vhead/>
<div class='main2'>
<Vaside/>
<Vcontent />
</div>
</div>
`,
methods:{
},
// 挂载子组件
components:{
Vhead,
Vaside,
Vcontent
}
};
new Vue({
el:"#app",
//(使用渲染局部组件App)
template:`<App></App>`,
// 挂载局部组件App
components:{
App
}
})
</script>