脚本宝典收集整理的这篇文章主要介绍了Vue2从0到1(四):Vue组件化及组件间传值,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以表现为用 is 特性进行了扩展的原生 HTML 元素。
组件A写法:
<template>
<div class="componentA">
...
</div>
</template>
<script>
export default {
data () {
return {
msg: 'component-A',
}
}
}
</script>
<style>
</style>
组件B写法:
<template>
<div class="message" id="componentB">
...
</div>
</template>
<script>
import Vue from 'vue'
export default Vue.component('my-component', {
template: '#componentB ',
data(){
return {
msg: 'component-B',
}
}
})
</script>
<style>
</style>
在父组件component
分别引用挂载
<template>
<div>
<component-A></component-A>
<component-B></component-B>
</div>
</template>
<script>
import componentA from './component-a.vue';
import componentB from './component-b.vue'
export default {
data () {
return {
}
},
components:{
"component-A":componentA,
"component-B":componentB
}
}
</script>
<style>
</style>
对于简单的父子组件或是同属同一父组件的兄弟组件之间的通信,vue提供了方法,没必要用到vuex
父组件:
<component-A :logo="logoMsg"></component-A> //logoMsg是父组件data里的值
子组件:
<template>
<div class="componentA">
<div>{{logo}}</div>
</div>
</template>
...
data(){
}
props:["logo"],
...
父组件:
<component-A :logo="logoMsg" @toParent="componenta"></component-A>
...
methods:{
componenta:function(data){ //data就是子组件传递过来的值
this.data1 = data
}
}
子组件:
methods:{
toParent:function(){
this.$emit('toParent',this.data1) //调用父组件toParent方法,并传递参数
}
}
效果图:
效果图:
bus.js文件:
import Vue from 'vue'
export default new Vue()
组件B $emit触发事件:
import Bus from './bus.js'
...
byBus:function(){
Bus.$emit('byBus',this.byBusData)
}
组件A $on接受事件传递数据
...
data(){
},
created(){
Bus.$on('byBus',(data)=>{
this.busData = data
})
},
效果图:
以上是脚本宝典为你收集整理的Vue2从0到1(四):Vue组件化及组件间传值全部内容,希望文章能够帮你解决Vue2从0到1(四):Vue组件化及组件间传值所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。