目录
一 点睛
Vue 的一大特性就是组件化。可以将 Vue 对象作为一个组件,被反复使用。
要想实现组件化,需要在页面中注册组件,注册组件有两种方式:全局注册和本地注册。
1 全局注册方式
Vue.component("组件名",{vue对象})
2 使用组件
在被 vue 绑定了html元素中才能使用组件。如果一个 div 没有被 vue绑定,那么这个 div 就不能使用之前注册的组件
3 作为组件的 vue 对象
Vue.component("组件名",{vue 对象}),这个 vue 对象和之前的 vue 对象的 data 实例属性的写法是有区别的。
// 之前的vue对象 data 的写法
new Vue(
data:{
name:'xiaoming',
age:29
}
)
// 作为组件化的 vue 对象 data 的写法
{
data:function(){
return:{
name:'xiaoming',
age:29
}
}
}
4 组件中 template 的写法
template 是将内容展现在页面上的一个键,值是一个字符串。一定要注意一点:template中有且仅有一个<div>根元素。
5 CDN——内容分发网络
这是一种加速策略,能够从离自己最近的服务器上快速获得外部资源。
6 CDN网站收录
Vue CDN收录:https://www.bootcdn.cn/vue/
二 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TodoList</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<!-- 挂载点 -->
<div id="root">
<div>
<input v-model="item" />
<button @click="handleadd">提交</button>
</div>
<ul>
<!-- 使用组件,通过:content和index设置组件属性,将数据传递给子组件 -->
<todo-item
v-for="(item,index) of items"
:key="index"
:content="item"
:index="index"
@delete="handledel">
</todo-item>
</ul>
</div>
<script type="text/javascript">
// 全局组件
Vue.component('todo-item',{
props: ['content', 'index'], // 组件的属性,通过props接受父组件传递的数据
template: '<li @click="onDelete" >{{content}}</li>', // 组件模板
methods: {
onDelete: function () {
this.$emit('delete', this.index) //触发delete事件,并将index数据传递给父组件
}
}
})
// 局部组件
// var TodoItem = {
// template: '<li>{{content}} <span @click="onDelete" style="background:gray; color:white">x</span></li>', // 组件模板
// }
// 实例,Vue实例就是一个组件
new Vue({
el: "#root",
// components: {
// 'todo-item': TodoItem, // 注册局部组件到vue实例
// },
data: {
item: "",
items: []
},
methods: {
handleadd: function () {
this.items.push(this.item);
this.item = ''
},
handledel: function (index) {
this.items.splice(index, 1)
}
}
})
</script>
</body>
</html>