Vue2从0到1(四):Vue组件化及组件间传值

发布时间:2019-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue2从0到1(四):Vue组件化及组件间传值脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

前面讲了环境的搭建用webpack打包vueVue-router的使用以及vuex的使用

下面讲一下Vue组件化及组件间传值:

主要包括 父子组件间传值,兄弟组件间传值,不相关组件间传值。

10.Vue组件化及组件间传值

10.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>

10.2组件间传值

对于简单的父子组件或是同属同一父组件的兄弟组件之间的通信,vue提供了方法,没必要用到vuex

10.2.1 父组件向子组件传值:

父组件:

    <component-A :logo="logoMsg"></component-A> //logoMsg是父组件data里的值

子组件:

   <template>
   <div class="componentA">
      <div>{{logo}}</div>
   </div>
</template>
   ...
   data(){

   }
   props:["logo"],
   ...

10.2.2子组件调用父组件方法并向父组件传值:

父组件:

   
   <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方法,并传递参数
        }
    }

效果图:

Vue2从0到1(四):Vue组件化及组件间传值

兄弟组件之间传值:在B组件修改父组件数据时。选择修改传给A组件的数据即可。

效果图:

Vue2从0到1(四):Vue组件化及组件间传值

10.2.3事件总线:不相关组件之间传递数据

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组件化及组件间传值

更复杂的数据传递就要用到vuex

代码托管于github 欢迎star

脚本宝典总结

以上是脚本宝典为你收集整理的Vue2从0到1(四):Vue组件化及组件间传值全部内容,希望文章能够帮你解决Vue2从0到1(四):Vue组件化及组件间传值所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:HTMLVue