Vue常用的三種傳值方式:
-
父傳子
-
子傳父
-
非父子傳值
引用官網一句話:父子組件的關系可以總結為 prop 向下傳遞,事件向上傳遞。父組件通過 prop 給子組件下發數據,子組件通過事件給父組件發送消息。
1. 父組件向子組件傳值:
父組件:
1 <template> 2 <div> 3 父組件: 4 <input type="text" v-model="name"> 5 <br> 6 <br> 7 <!-- 引入子組件 --> 8 <child :inputName="name"></child> 9 </div> 10 </template> 11 <script> 12 import child from './child' 13 export default { 14 components: { 15 child 16 }, 17 data () { 18 return { 19 name: '' 20 } 21 } 22 } 23 </script>
子組件:
1 <template> 2 <div> 3 子組件: 4 <span>{{inputName}}</span> 5 </div> 6 </template> 7 <script> 8 export default { 9 // 接受父組件的值 10 props: { 11 inputName: String, 12 required: true 13 } 14 } 15 </script>
2. 子組件向父組件傳值:
子組件:
1 <template> 2 <div> 3 子組件: 4 <span>{{childValue}}</span> 5 <!-- 定義一個子組件傳值的方法 --> 6 <input type="button" value="點擊觸發" @click="childClick"> 7 </div> 8 </template> 9 <script> 10 export default { 11 data () { 12 return { 13 childValue: '我是子組件的數據' 14 } 15 }, 16 methods: { 17 childClick () { 18 // childByValue是在父組件on監聽的方法 19 // 第二個參數this.childValue是需要傳的值 20 this.$emit('childByValue', this.childValue) 21 } 22 } 23 } 24 </script>
父組件:
1 <template> 2 <div> 3 父組件: 4 <span>{{name}}</span> 5 <br> 6 <br> 7 <!-- 引入子組件 定義一個on的方法監聽子組件的狀態--> 8 <child v-on:childByValue="childByValue"></child> 9 </div> 10 </template> 11 <script> 12 import child from './child' 13 export default { 14 components: { 15 child 16 }, 17 data () { 18 return { 19 name: '' 20 } 21 }, 22 methods: { 23 childByValue: function (childValue) { 24 // childValue就是子組件傳過來的值 25 this.name = childValue 26 } 27 } 28 } 29 </script>
3. 非父子組件傳值:
非父子組件之間傳值,需要定義個公共的公共實例文件bus.js,作為中間倉庫來傳值,不然路由組件之間達不到傳值的效果。
公共 bus.js
1 //bus.js 2 import Vue from 'vue' 3 export default new Vue()
組件A:
1 <template> 2 <div> 3 A組件: 4 <span>{{elementValue}}</span> 5 <input type="button" value="點擊觸發" @click="elementByValue"> 6 </div> 7 </template> 8 <script> 9 // 引入公共的bug,來做為中間傳達的工具 10 import Bus from './bus.js' 11 export default { 12 data () { 13 return { 14 elementValue: 4 15 } 16 }, 17 methods: { 18 elementByValue: function () { 19 Bus.$emit('val', this.elementValue) 20 } 21 } 22 } 23 </script>
組件B:
1 <template> 2 <div> 3 B組件: 4 <input type="button" value="點擊觸發" @click="getData"> 5 <span>{{name}}</span> 6 </div> 7 </template> 8 <script> 9 import Bus from './bus.js' 10 export default { 11 data () { 12 return { 13 name: 0 14 } 15 }, 16 mounted: function () { 17 var vm = this 18 // 用$on事件來接收參數 19 Bus.$on('val', (data) => { 20 console.log(data) 21 vm.name = data 22 }) 23 }, 24 methods: { 25 getData: function () { 26 this.name++ 27 } 28 } 29 } 30 </script>
每日壹題:
打印出 1 - 10000 之間的所有對稱數
1 console.log([...Array(10000).keys()].filter((x) => { 2 return x.toString().length > 1 && x === Number(x.toString().split('').reverse().join('')) 3 }))