组件是Vue.js最强大的功能之一。组件可以扩展HTML元素,封装可重用的代码。在较高层面上,组件是自定义的元素,Vue.js的编译器为它添加特殊功能。在有些情况下,组件也可以是原生HTML元素的形式,以is特性扩展。
1、注册组件
注册组件就是利用Vue.component()
方法,先传入一个自定义组件的名字,然后传入这个组件的配置。
Vue.component('mycomponent',{
template: `<div>这是一个自定义组件</div>`,
data () {
return {
message: 'hello world'
}
}
});
挂载到DOM元素中,使用
<div id="app">
<mycomponent></mycomponent>
<my-component></my-component>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
},
components: {
'my-component': {
template: `<div>这是一个局部的自定义组件,只能在当前Vue实例中使用</div>`,
}
}
})
</script>
直接使用Vue.component()
创建的组件,所有的Vue实例都可以使用。还可以在某个Vue实例中注册只有自己能使用的组件。
var app = new Vue({
el: '#app',
data: {
},
components: {
'my-component': {
template: `<div>这是一个局部的自定义组件,只能在当前Vue实例中使用</div>`,
}
}
})
注意:组件的模板只能有一个根元素。
属性Props (父组件是使用 props 传递数据给子组件)
Vue.component('mycomponent',{
template: '<div>这是一个自定义组件,父组件传给我的内容是:{{myMessage}}</div>',
props: ['myMessage'], // 自定义特性
data () {
return {
message: 'hello world'
}
}
})
html:
<my-component :my-message="message"><//my-component>
new Vue({
data:{
message:'Hello World'
}
})
自定义事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.counter += 1
this.$emit('increment',this.counter) // 触发父组件的方法, 事件名称为全小写
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function (value) {
this.total = value
}
}
})
</script>
</body>
</html>