【Vue】组件间传值的三种方式:父传子,子传父,非父子传值
引用官網的一句話:父子組件的關系可以總結為 prop 向下傳遞,事件向上傳遞。父組件通過 prop 給子組件下發數據,子組件通過事件給父組件發送消息,如下圖所示:
1,父組件傳值給子組件
代碼:
<template><div style="padding: 20px;"><span>父組件</span><input type="text" v-model="textInfo" /><ChildInfo :textInfo="textInfo"></ChildInfo></div> </template><script> import ChildInfo from '../../views/ChildInfo' export default {name: 'Home',components: {ChildInfo},data () {return {textInfo: ''}} } </script> <style scoped></style> <template> <div><span>我是子組件:{{textInfo}}</span> </div> </template><script> export default {name: 'ChildInfo',props: {textInfo: {type: String,required: true}} } </script><style scoped></style>2,子組件傳值給父組件
<template><div style="padding: 20px;"><span>父組件</span><input type="text" v-model="textInfo" /><ChildInfo v-on:funb="funb"></ChildInfo></div> </template><script> import ChildInfo from '../../views/ChildInfo' export default {name: 'Home',components: {ChildInfo},data () {return {textInfo: ''}},methods: {funb (a) {this.textInfo = a}} } </script> <style scoped></style> <template> <div><span>我是子組件:{{textInfo}}</span><button @click="funa"> 發送數據</button> </div> </template><script> export default {name: 'ChildInfo',data () {return {textInfo: '我是子組件的數據'}},methods: {funa () {this.$emit('funb', this.textInfo)}} } </script><style scoped></style>3,非父子組件傳值
非父子組件之間傳值,需要定義個公共實例文件bus.js,作為中間倉庫來傳值,不然路由組件之間達不到傳值的效果。
bus文件可以理解為組件A和B的父組件,組件A注冊一個事件上浮給bus文件,組件B在bus文件下監聽事件
// bus.js import Vue from 'vue' export default new Vue() <template> <div>A組件:<span>{{elementValue}}</span><input type="button" value="點擊觸發" @click="elementByValue"> </div> </template><script> import Bus from './bus' export default {name: 'ChildInfo',data () {return {elementValue: 10}},methods: {elementByValue: function () {Bus.$emit('val', this.elementValue)}} } </script><style scoped></style> <template> <div>B組件:<span>{{elementValue}}</span> </div> </template><script> import Bus from './bus' export default {name: 'ChildInfo2',data () {return {elementValue: 0}},mounted: function () {var that = this// 用$on事件來接收參數Bus.$on('val', (data) => {that.elementValue = data})},methods: {} } </script><style scoped></style>延申閱讀:
vue中非父子組件之間通信除了使用bus總線,也可以使用vuex,兩者適用場景不同。
bus適合小項目、數據被更少組件使用的項目,對于中大型項目 數據在很多組件之間使用的情況 bus就不太適用了。bus其實就是一個發布訂閱模式,利用vue的自定義事件機制,在觸發的地方通過$emit向外發布一個事件,在需要監聽的頁面,通過$on監聽事件。
vuex適用中大型項目、數據在多組件之間公用的情況。
發布訂閱模式:
在軟件架構中,發布訂閱是一種消息范式,消息的發送者(稱為發布者)不會將消息直接發送給特定的接收者(稱為訂閱者)。而是將發布的消息分為不同的類別,無需了解哪些訂閱者(如果有的話)可能存在。同樣的,訂閱者可以表達對一個或多個類別的興趣,只接收感興趣的消息,無需了解哪些發布者(如果有的話)存在。
參考文章:
Vue2.0的三種常用傳值方式、父傳子、子傳父、非父子組件傳值_lander_xiong的博客-CSDN博客_vue 父傳子
總結
以上是生活随笔為你收集整理的【Vue】组件间传值的三种方式:父传子,子传父,非父子传值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch读取常用数据集datase
- 下一篇: 对8421码,5421码,2421码,余