Vue组件通讯

  Vue最常用的组件通讯有三种:父->子组件通讯、子->父组件通讯,兄弟组件通讯.(template用的pug模板语法)

1.父->子组件通讯

  父->子组件通讯,是通过props进行数据传递,并且具有这几个特性,单向传递,子组件接收的数据不可以更改,如果更改,会发出警告,每次父组件更新时,子组件的所有 prop 都会更新为最新值.

 1 父组件
 2 <template lang="pug">
 3    .father
 4      Children(:name='msg')
 5 </template>
 6 <script>
 7 
 8 import Children from './Children'
 9 export default {
10  name: 'father',
11    data () {
12      return {
13        msg: '我是father的数据'
14      }
15    }
16  }
17 </script>
1 子组件
2  <template lang="pug">
3   .children
4     .box {{name}}
5 </template>
6 
7 <script>
8 export default {
9   name: 'father',
10   // props: ['name'],  1.props的第一种写法
11   // props: {      2.props的第二种写法
12   //   name: Array
13   // },
14   props: {        3.props的第三中写法(推荐)
15     name: {
16       type: String
17     }
18   },
19   data () {
20     return {
21       msg: '我是children的数据'
22     }
23   }
24 }
25 </script>
 1 2.子->父组件通讯
 2  
 3    一般子->父组件通讯是通过Events事件进行值得传递
 4  
 5  父组件
 6   <template lang="pug">
 7    .father
 8      Children(@hand='hand') //自定义事件1 </template>
 9  
10 <script>
11 import Children from './Children'
12 export default {
13   name: 'father',
14  data () {
15     return {
16       msg: '我是father的数据'
17     }
18   },
19   components: {
20      Children
21    },
22   methods: {
23     hand (msg) {
24       alert(msg)  //拿到子组件传递的值
25     }
26   }
27 }
28 </script>
 1 子组件
 2 <template lang="pug">
 3   .children
 4     input(type='button' value='clickMe' @click='handle')
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: 'children',
10   data () {
11     return {
12       msg: '我是children的数据'
13     }
14   },
15   methods: {
16     handle () {
17       this.$emit('hand', this.msg)  //发送事件名+传递的值
18     }
19 }
20 </script>

 

3.兄弟组件通讯

  由上可知,父子组件通讯都会有一个媒介,相当于一个传递信息的介质,才可以使得数据传递过去。兄弟组件通讯业需要一个介质,我们通常称之为事件线~

1.创建一个组件  名字:eventBus(随便起) 我放在了src/asstest/eventBus/index.js文件夹下

1 import Vue from 'vue'
2 export default new Vue()

2.创建第一个兄弟组件,名字:Emit

 1 <template lang="pug">
 2   .emit
 3     .box Emit组件a
 4     button(@click='show') 向on组件传值
 5 </template>
 6 
 7 <script>
 8 import bus from '../assets/eventBus'
 9 export default {
10   methods: {
11     show () {
12       bus.$emit('user', 'haha')  
13     }
14   }
15 }
16 </script>

3.创建第二个兄弟组件,名字:On

 1 <template lang="pug">
 2   .on
 3     .cont 接受emit组件的数据:{{msg}}
 4 </template>
 5 
 6 <script>
 7 import bus from '../assets/eventBus'
 8 export default {
 9   data () {
10     return {
11       msg: 'on'
12     }
13   },
14   mounted () {
15     let self = this
16     bus.$on('user', (msg) => {
17       self.msg = msg
18     })
19   }
20 }
21 </script>

 

  在vue中常用的传值方式也就是这三种,但方放不局限于这三种。希望喜欢我的小伙伴们继续支持我。

 

  

  

posted @ 2018-07-02 19:23  阿龙丶along  阅读(362)  评论(0编辑  收藏  举报