vue2.0 组件化及组件传值
2017-12-19 10:17
435 查看
组件 (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>
<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>
<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方法,并传递参数 } }
效果图:
兄弟组件之间传值:在B组件修改父组件数据时。选择修改传给A组件的数据即可。
效果图:
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 父组件传值给子组件初始化用
- vue2.0组件之间传值、通信的多种方式(干货)
- Vue2.0 子组件传值给父组件
- vue2.0组件之间的传值
- vue2.0 子组件 父组件之间的传值
- Vue2.0的通用组件
- Vue 2.0 起步(2) 组件及 vue-router实例 - 微信公众号RSS
- VUE之父子组件间传值
- vue2.0使用weui.js的uploader组件上传图片
- vue2.0 组件和v-model
- Vue 2.0学习笔记:实现组件数据的双向绑定
- vue2.0父子组件通信(慕课网)
- vue平行组件传值 params
- vue2.0 使用element-ui里的upload组件实现图片预览效果方法
- Vue2.0组件之间通信
- vue1.0与vue2.0区别之组件通信
- [js高手之路]Vue2.0基于vue-cli+webpack同级组件之间的通信教程
- Vue 2.0学习笔记:Vue组件内容分发(slot)
- VUE2.0父子组件以及非父子组件通信传参详解
- vue.js2.0 自定义组件初体验