1,组件(component) 是vue最强大的功能之一,组件化开发
2,vue组件可以扩展html元素,封装可重用的代码
3,在组件中,data是函数,并且有返回值
4,全局组件
<div id="app">
<my-component></my-component>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component('my-component',{
template:`
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
`
})
new Vue({
el:'#app'
})
5,局部组件
<div id="app">
<my-component></my-component>
<div>
<h1>asdas</h1>
<button>按钮</button>
</div>
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el:'#app',
components:{
template:`
<div>
<h1>asdas</h1>
<button>按钮</button>
</div>
`,
data:function(){
return{
msg:'12312'
}
},
methods:{
alt:function(){
alert(221341);
}
}
}
})
</script>
6,组件之间的传值
父传子-----用属性传
子传父-----用事件传
同级之间传值(兄弟关系)
(父传子)
<div id='app'>
<my-content></my-content>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-content",{
template:`
<div>
<h2>我是my-content组件的标题</h2>
<my-child v-bind:message='msg'></my-child>
</div>
`,
data:function(){
return{
msg:'dgddbghfghfnh'
}
}
})
Vue.component("my-child",{
props:['message'],
template:`
<div>
<h3>我是my-child组件中的标题</h3>
<p>{{message}}</p>
</div>
`
})
new Vue({
el:'#app'
})
</script>
(子传父)
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('my-father',{
template:`
<div>
<h1>{{mess}}</h1>
<my-child @send='revMsg'></my-child>
</div>
`,
data:function(){
return{
mess:''
}
},
methods:{
revMsg:function(txt){
this.mess=txt
}
}
})
Vue.component('my-child',{
template:`
<button @click='sendFather'>给父组件</button>
`,
data:function(){
return{
msg:'-----------'
}
},
methods:{
sendFather:function(){
// this.$emit('自定义事件',参数)
this.$emit('send',this.msg)
}
}
})
new Vue({
el:"#app"
})
</script>
网友评论