Vue最常用的組件通訊有三種:父->子組件通訊、子->父組件通訊,兄弟組件通訊.(template用的pug模板語法)


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中常用的傳值方式也就是這三種,但方放不局限於這三種。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM