vue组件之间的通信

mac2025-02-06  16

作为一个vue初学者不得不了解的就是组件间的数据通信(暂且不谈vuex)。通信方式根据组件之间的关系有不同之处。组件关系有下面三种:父-->子、子-->父、非父子

父-->子


父向子传递数据通过props


**父组件代码** <template> <header-box :title-txt="showTitleTxt"></header-box> </template> <script> import Header from './header' export default { name: 'index', components: { 'header-box': Header }, data () { return { showTitleTxt: '首页' } } } </script> **子组件代码** <template> <header> {{thisTitleTxt}} </header> </template> <script> export default { name: 'header-box', props: { titleTxt: String }, data () { return { thisTitleTxt: this.titleTxt } } } </script>

子-->父


子组件向父组件传递分为两种类型。 1、子组件改变父组件传递的props(你会发现通过props中的Object类型参数传输数据,可以通过子组件改变数据内容。这种方          式是可行的,但是不推荐使用,因为官方定义prop是单向绑定) 2、通过on和emit


*通过props实现传递* **父组件代码** <template> <header-box :title-txt="showTitleTxt"></header-box> </template> <script> import Header from './header' export default { name: 'index', components: { 'header-box': Header }, data () { return { showTitleTxt: { name: '首页' } } } } </script> **子组件代码** <template> <header @click="changeTitleTxt"> {{thisTitleTxt.name}} </header> </template> <script> export default { name: 'header-box', props: { titleTxt: Object }, data () { return { thisTitleTxt: this.titleTxt.name } }, metheds: { changeTitleTxt () { this.titleTxt.name = '切换' } } } </script> *通过$on,$emit* **父组件代码** <template> <div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> </div> </template> <script> import ButtonCounter from './buttonCounter' export default { name: 'index', components: { 'button-conuter': ButtonCounter }, data () { return { total: 0 } }, methods: { incrementTotal () { this.total++ } } } </script> **子组件代码** <template> <button @click="incrementCounter">{{counter}}</button> </template> <script> export default { name: 'button-counter', data () { return { counter: 0 } }, metheds: { incrementCounter () { this.$emit('increment') this.counter++ } } } </script>

非父子


简单情况下我们可以通过使用一个空的Vue实例作为中央事件总线,(这里也可以使用app实例,而不需要新建一个空Vue实例)


**main.js** let bus = new Vue() Vue.prototype.bus = bus

或者

**main.js** new Vue({ el: '#app', router, template: '<App/>', components: { App }, beforeCreate () { Vue.prototype.bus = this } }) **header组件** <template> <header @click="changeTitle">{{title}}</header> </template> <script> export default { name: 'header', data () { return { title: '头部' } }, methods: { changeTitle () { this.bus.$emit('toChangeTitle','首页') } } } </script> **footer组件** <template> <footer>{{txt}}</footer> </template> <script> export default { name: 'footer', mounted () { this.bus.$on('toChangeTitle', function (title) { console.log(title) }) }, data () { return { txt: '尾部' } } }

 

最新回复(0)