组件注册
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="app1">
<button-text ></button-text>
<parttest ></parttest>
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('button-text',{
data(){
return{
title:"我是子组件的title",
}
},
template:'<button type="button">{{title}} </button>',
})
var vm=new Vue({
el:'#app1',
})
let parttest = {
template:'<button type="button">局部注册</button>'
}
var vm=new Vue({
el:'#app1',
components:{parttest}
})
</script>
</html>
自定义属性props
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="app1">
<button-text titleprop1="使用自定义的属性"></button-text>
<button-text :titleprop1="titletest1"></button-text>
<button-text ></button-text>
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('button-text',{
data(){
return{
title:"我是子组件",
}
},
props:{
titleprop1:{
type:String,
require:true,
default:"我是一个默认值"
}
},
template:' <button type="button">{{titleprop1}}</button>',
})
var vue_component=new Vue({
el:'#app1',
data(){
return{
titletest1:"我是父组件的值"
}
},
})
</script>
</html>
自定义事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="app1">
<button-text :titleprop1="titletest1" @myevent="pearentfun"></button-text>
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('button-text',{
data(){
return{
title:"我是子组件",
}
},
template:'<button type="button" @click="clickme">{{title}}</button>',
methods:{
clickme(){
this.$emit("myevent",{name:"我是子组件的参数name值"})
}
}
})
var vue_component=new Vue({
el:'#app1',
data(){
return{
titletest1:"我是父组件的值"
}
},
methods:{
pearentfun(obj){
console.log("你现在点击的是子组件传过来的一个自定义事件哦!")
console.log("参数name:",obj.name)
}
}
})
</script>
</html>
插槽
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="app1">
<button-text >我是父组件,我要使用子组件的插槽</button-text>
<button-text >{{titletest1}}</button-text>
<button-text ></button-text>
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('button-text',{
data(){
return{
title:"我是子组件",
}
},
template:' <button type="button"><slot>插槽</slot></button>',
})
var vue_component=new Vue({
el:'#app1',
data(){
return{
titletest1:"我是父组件的值"
}
},
})
</script>
</html>