Vue.js 组件
组件(Component)是 Vue.js 最强大的功能之一。
组件可以扩展 HTML 元素,封装可重用的代码。
组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树
全局组件
全局组件,一次定义,就可以直接调用
<div id="root">
<todo-item></todo-item>
</div>
<script>
// 注册
Vue.component('todo-item', {
template: '<h1>自定义组件!</h1>'
})
// 创建根实例
new Vue({
el: '#root'
})
</script>
局部组件
局部组件,需要在Vue实例
中的compoents
中注册它,不然就不能被使用报错: 组件未注册
<div id="root">
<todo-item></todo-item>
</div>
<script>
var Child = {
template: '<h1>自定义组件!</h1>'
}
// 创建根实例
new Vue({
el: '#root',
components: {
// <todo-item> 将只在父模板可用
'todo-item': Child
}
})
</script>
prop
当我们定义好组件之后(自定义组件都是子组件
),(Vue实例可以看成是一个父组件
)需要往组件里面传递数据的时候,需要用到props
这个属性,不然你的数据不会被组件接收到
下面content
是我自己定义的一个属性(这里你可以随便写什么,什么就是属性
)
<div id="root">
<div>
<input v-model="inputValue"/>
<button @click="handleSubmit">提交</button>
<ul>
<todo-item
v-for="(item , index) of list"
:key="index"
:content="item"
>
</todo-item>
</ul>
</div>
</div>
<script>
//全局组件,一次定义,就可以直接调用
Vue.component('todo-item', {
props:['content'],
template: '<li>{{content}}</li>'
})
new Vue({
el: "#root",
data: {
inputValue: "hello",
list: []
},
methods: {
handleSubmit: function () {
this.list.push(this.inputValue)
this.inputValue = ''
}
}
})
</script>
组件和实例
自定义组件
都是Vue实例
。上面自定义组件在名为Root根Vue实例
中使用了另一个Vue实例(自定义组件)
,所以根Vue实例就是父组件
,自定义组件就是子组件
Vue项目就是由很多个这样的Vue实例组成,所有它的父子关系也就有很多
自定义事件
子组件自定义事件的时候,数据无法直接从子组件
传递到父组件
,这里需要通过$emit
来触发事件。在自定义组件中,写一个触发事件,调用$emit
去触发delete
事件,携带一个index
参数。子组件中注册一个delete
的事件,触发handleDelete
事件,从而调用父组件的方法,并且将子组件的参数
传递过去
<div id="root">
<div>
<input v-model="inputValue"/>
<button @click="handleSubmit">提交</button>
<ul>
<todo-item
v-for="(item , index) of list"
:key="index"
:content="item"
:index="index"
@delete="handleDelete"
>
</todo-item>
</ul>
</div>
</div>
<script>
//全局组件,一次定义,就可以直接调用
Vue.component('todo-item', {
props:['content',"index"],
template: '<li @click="handleClick">{{content}}</li>',
methods: {
handleClick:function () {
this.$emit('delete',this.index)
}
}
})
new Vue({
el: "#root",
data: {
inputValue: "hello",
list: []
},
methods: {
handleSubmit: function () {
this.list.push(this.inputValue)
this.inputValue = ''
},
handleDelete:function (index) {
alert(index)
this.list.splice(index,1)
}
}
})
</script>