- 全局组件
<body>
<div id="app">
<child ></child>
</div>
<script>
// 全局组件
Vue.component('child',{
template:'<h1>child<h1/>'
})
new Vue({
el:"#app"
})
</script>
</body>
- 局部组件
<body>
<div id="app">
<child ></child>
</div>
<script>
var childComponent = {
template:"<h1>局部组件<h1/>"
}
// 局部组件
new Vue({
el:"#app",
components:{
'child':childComponent
}
})
</script>
</body>
- props属性
<body>
<div id="app">
<child message="test"></child>
</div>
<script>
//prop
Vue.component('child',{
props:['message'],
template:'<h1>{{message}}<h1/>'
})
new Vue({
el:"#app"
})
</script>
</body>
- 动态绑定
<body>
<div id="app">
<input type="text" v-model="message">
<child v-bind:test="message"></child>
</div>
<script>
//prop动态绑定
Vue.component('child',{
props:['test'],
template:'<h1>{{test}}<h1/>'
})
new Vue({
el:"#app",
data:{
message:'test'
}
})
</script>
</body>
<body>
<div id="app">
<ol>
<child v-for="item in message" :test="item"></child>
</ol>
</div>
<script>
//prop动态绑定
Vue.component('child',{
props:['test'],
template:'<li>{{test.name}}</li>'
})
new Vue({
el:"#app",
data:{
message:[
{name:'小明'},
{name:'小红'},
{name:'小李'},
]
}
})
</script>
</body>
- 类型验证
<body>
<div id="app">
<ol>
<child v-for="item in message" test="item"></child>
</ol>
</div>
<script>
//prop动态绑定
Vue.component('child',{
props:{
test: {
type: Object,
required:true
}
},
template:'<li>{{test.name}}</li>'
})
new Vue({
el:"#app",
data:{
message:[
{name:'小明'},
{name:'小红'},
{name:'小李'},
]
}
})
</script>
</body>
- 子组件自定义方法
<body>
<div id="app">
{{count}}
<br/>
<child-component :init-value=count @add-event="addFunction"></child-component>
</div>
<script>
Vue.component('child-component',{
props:['initValue'],
data:function () {
return{
countValue:this.initValue
};
},
template:'<button @click="addFunction">{{countValue}}</button>',
methods:{
addFunction: function () {
this.countValue++;
this.$emit('add-event');
}
},
})
new Vue({
el:"#app",
data:{
count:"11"
},
methods: {
addFunction:function () {
this.count++;
}
}
})
</script>
</body>
- 注意
- html不区分大小写,所以往往中间用横线连接。并且vue内部往往会把相应的横线链接的变成驼峰命名的方式。
- html不区分大小写,会把所有大写字母解析成小写字母。