Vue 组件
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue todolist</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="root">
<div>
<input v-model='inpVal'>
<button @click='submit'>添加</button>
</div>
<ul>
<todo-item
v-for='(item,index) of list'
:key='index'
:index='index'
:content='item'
@delete='delFun'
></todo-item>
</ul>
</div>
</body>
</html>
vue js
//全局组件
Vue.component('todoItem',{
props:['content','index'],
template:'<li @click='handelDel'>{{content}}</li>',
methods:{
handelDel:function(){
this.$emit('handel',this.index);
}
}
});
// //局部组件
// var todoItem={
// template:'<li>item</li>'
// }
new Vue({
el:'#root',
data:{
inpVal:'',
list:[]
},
computed:{//计算属性
},
watch:{//侦听器
},
methods:{
//方法
submit:function(){
this.list.push(this.inpVal);
this.inpVal='';
},
delFun:function(index){
this.list.splice(index,0);
}
}
});
- 全局组件
Vue.component('todo-item',{
template:'<li>item</li>'
});
- 通过component创建的组件为全局组件,可以在任何地方通过<todo-item></todo-item>调用
- 局部组件
var todoItem={
template:'<li>item</li>'
}
- 局部组件直接在实例模板里调用是调用不了的 会报组件未被注册 需要在最外层的
new Vue()实例里边通过components对局部组件进行声明 如:
new Vue(){
el:'#root',
components:{
todo-item:todoItem
}
}
- 父组件给子组件传参
可以在自组件自定义属性传参 这里用的全局组件为例 如:
<ul>
<todo-item
v-for='(item,index) of list'
:key='index'
:content='item'
:index='index'
@delete='delfun'
>
</todo-item>
</ul>
//全局组件
Vue.component('todo-item',{
props:['content','index'],
template:'<li @click="handelDel">{{content}}</li>',
methods:{
handelDel:function(){
this.$emit('handelDel',this.index);
}
}
});
//局部组件
var todoItem={
props:['content'],
template:'<li>{{content}}</li>'
};
- 子组件与父组件的通信
- 通过this.emit发出父组件自定义的函数
vue组件与实例的关系
- 每一个vue的组件都是是一个vue的实例
vue的项目都是由千千万万个vue的实例组成的 - 在组件里也可以定义methods等方法
Vue.component('todo-item',{
props:['content'],
template:'<li @click="handel">{{content}}</li>',
methods:{
handel:function(){
}
}
});

浙公网安备 33010602011771号