vue组件创建
Vue组件是Vue最强大的功能之一
可以扩展HTML元素,可以封装可重用的代码块
优点:
1.可以减少代码的重用,提高开发效率
2.减低页面的耦合度,使页面更方便维护与管理
局部组件
new Vue({
el:"#app",
data:{}, // 数据
methods:{}, // 函数,方法
computed:{}, // 计算属性
filters:{}, // 过滤器
watch:{}, // 侦听器
components:{//局部
'my-component':{ // 组件名
template:` // html模板
<div>
<h1>hello component</h1>
<input>
</div>
`//模板 html元素
}
}
})
全局组件
Vue.component('my-component',{
template:`
<div>
<h1>这是全局组件</h1>
<input>
</div>
`,
data:function(){
return{
}
},
methods:{
}
})
new Vue({
el:"#app"
})
组件的嵌套
<script>
Vue.component('my-component',{
template:`
<div>
<p>{{msg}}</p>
</div>
`,
data:function(){
return{
msg:'hello vue'
}
}
})
Vue.component('father',{
template:`
<div>
<h1>我是父组件</h1>
<my-component></my-component>
</div>
`
})
new Vue({
el:"#app",
})
</script>
组件间的通信
父组件给子组件传值
在父组件的使用的时候讲数据作为参数传给子组件,在子组件中使用props定义属性, props:[‘text’]
<script>
Vue.component('pa',{
template:`
<div>
<h1>我是父组件</h1>
<my v-bind:txt="msg"></my>
</div>
`,
data:function(){
return{
msg:'我是父组件中的数据,要传给给子组件'
}
}
})
Vue.component('my',{
//传一个属性
props:['txt'],
template:`
<div>
<h1>我是子组件</h1>
<p>{{txt}}</p>
</div>
`
})
new Vue({
el:"#app"
})
</script>
//vue实例给组件传值
<script>
Vue.component('pr',{
props:['txt'],
template:`
<div>
<h1>{{txt}}</h1>
</div>
`
})
new Vue({
el:"#app",
data:{
msg:'hello vue'
}
})
</script>
子组件给父组件传值
用 $emit (‘事件’,属性)传值,然后在父组件中调用方法事件,然后用虚参接受值,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<fu></fu>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component('fu',{
template:`
<div>
<h1> 这是父组件</h1>
<ul>
<li v-for='item in arra'>{{item}}</li>
</ul>
<pi @inval='invala' :tit='name1'></pi>
<pi @inval='invala' :tit='name2'></pi>
</div>
`,
data:function(){
return{
name1:'lll',
name2:'zzzz',
arra:[]
}
},
methods:{
invala(vas){
this.arra.push(vas);
}
}
})
Vue.component('pi',{
template:`
<div>
<label id='in'>{{tit}}</label>
:<input name='in' type='text' v-model='val'>
<input type='button' value='发送' @click='tjs'>
</div>
`,
props:['tit'],
data:function(){
return{
val:'',
}
},
methods:{
tjs:function(){
this.$emit('inval', this.val);
this.val='';
}
}
})
let vm = new Vue({
el:'#app',
data:{}
})
</script>
</body>
</html>