vue的组件面面观 / 网络研习社#14
和小程序一样,有个组件概念的出现。它的使用,就是为了拆分Vue实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可,简直不要太方便!
全局组件component定义的三种方式 :
第一种方法
1、var con = Vue.extend({
template: '<span> hello world</span>'
})
2、Vue.component('name', 模板对象)
Vue.component('mycon',con)
3、<div><mycon></mycon></div>
可以简写为:
1、Vue.component('mycon',Vue.extend({
template: '<span> hello world</span>'
}))
2、<div><mycon></mycon></div>
第二种方法
1、Vue.component('mycon', {
template: '<span> hello world</span>'
})
2、<div><mycon></mycon></div>
第三种方法
全局组件
1、Vue.component('mycon', {
template: '#tmp'
})
2、<template id="tmp">
<div>hello world</div>
</template>
3、<div><mycon></mycon></div>
私有组件
<div><mycon></mycon></div>
定义私有方法components:
components:{
mycon: {
template: '<span> hello world</span>'
}
}
组件中的data,必须是函数,return出去:
Vue.component('mycon', {
template: '#tmp',
data: function () {
return {msg: '组件中的数据'}
}
})
组件切换:
<div id="app">
<a href="" @click.prevent="name='mycon1'">mycon1</a>
<a href="" @click.prevent="name='mycon2'">mycon2</a>
<component :is="name"></component>
</div>
Vue.component('mycon1', {
template: '#tmp1'
})
Vue.component('mycon2', {
template: '#tmp2'
})
var app = new Vue({
el: '#app',
data: {
name: 'mycon1'
}
})
父组件向子组件传值--props[]
<div id="app">
<mycon :parentmsg='msg'></mycon>
</div>
<template id="tmp">
<div>
<h1>我是一个组件---{{ parentmsg}}</h1>
</div>
</template>
<script>
var app = new Vue({
el: '#app',
data: {
msg: '父组件中的数据'
},
components: {
mycon : {
template: '#tmp',
props: ['parentmsg']
}
}
})
</script>
父组件向子组件传递方法,子组件向父组件传值--$emit()
<div id="app">
<mycon @func='show'></mycon>
</div>
<template id="tmp">
<div>
<input type="button" value="调用" @click="myclick">
</div>
</template>
<script>
var app = new Vue({
el: '#app',
data: { },
methods: {
show: function (data) {
console.log('父组件中的方法' + data) //可以通过这种方法,子组件向父组件传值
}
},
components: {
mycon : {
template: '#tmp',
methods: {
myclick: function () {
this.$emit('func', 123)
}
}
}
}
})
</script>
网络研习社系列文章:
- 微信小程序开发初体验 / 网络研习社#1
- 新技能:小程序空间当图床! / 网络研习社#2
- 小程序云开发中数据的传递形式 / 网络研习社#3
- 如何突破coreldraw的网络限制 / 网络研习社#4
- 我师网小程序初发布,大家多多指教 / 网络研习社#5
- 用github 做文件目录 / 网络研习社#6
- LNMP环境一键安装(一) / 网络研习社#7
- LNMP环境自定义安装(二) / 网络研习社#8
- 利用github做免费博客 / 网络研习社#9
- Nodejs,打开服务器黑匣子 / 网络研习社#10
- 一入前端深似海,聊聊vue.js / 网络研习社#11
- 我们想做的,vue都帮我们做好了 / 网络研习社#12
- vue和小程序一家亲 / 网络研习社#13
看来可以和小程序一起学了!
Congratulations @lemooljiang! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :
You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP
To support your work, I also upvoted your post!
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!