目录
  • 1、props
    •  父 >>> 子  (props)
    • 子 >>> 父 ($emit)
  • 2、bus事件总线
    • 3、vuex状态管理库
      •  4、router
        •  5、缓存

                  以下是我在开发中用到过的vue组件之间的通信方式,不同的场景使用不同的方式,基本满足所有开发场景中的通信需求,从最简单的事例着手,讲述如何使用,话不多说直接开始,满满的干货,建议看完。

          1、props

           父 >>> 子  (props)

          一个组件里面引入另外一个组件,此时构成了一种“父子关系”,当前组件为“父”,引入的组件为“子”,如当前组件(父),在父组件中通过 “:message” 向子组件通信。

          <template>
              <div class="parent-box">
                  <div>
                      <div>我是父页面</div>
                      <div>{{message}}</div>
                  </div>
                  <children :message="tochildrenmsg"></children>
              </div>
          </template>
           
          <script>
          import children from './children.vue'  //当前页引入子组件
          export default {
              name:"parent",
              components:{
                  children
              },
              data(){
                  return {
                      message:'我是父页面的内容',
                      tochildrenmsg:'从父页面传过到子页面的内容'
                  }
              }
          }
          </script>

          在子组件通过props进行接收,注意子组件props里面接收的对象名称必须与父组件中在子组件绑定的名称一致,当前例子为“message”,可以在组件return中this.的方式使用props里面的值。

          <template>
              <div class="children-box">
                  <div>
                      <div>我是子页面</div>
                      <div>{{message}}</div>
                  </div>
              </div>
          </template>
           
          <script>
          export default {
              name:"children",
              props:{
                  message:{
                      type:string,  //类型判断
                      default:''    //默认值
                  }
              }
          }
          </script>

            子组件接收到父组件传过来的内容,实现效果如下图所示:

          子 >>> 父 ($emit)

          在子组件中通过this.$emit()方法向父组件通信,如下,点击触发事件,执行this.$emit(‘fromchildmethod’),触发父组件的fromchildmethod方法。

          <template>
              <div class="children-box">
                  <div>
                      <div>我是子页面</div>
                      <div>{{message}}</div>
                      <div><span @click="toparentmethod">点击触发父页面事件</span></div>
                  </div>
              </div>
          </template>
           
          <script>
          export default {
              name:"children",
              props:{
                  message:{
                      type:string,
                      default:''
                  }
              },
              methods:{
                  toparentmethod(){
                      this.$emit('fromchildmethod')
                  }
              }
          }
          </script>

          在父组件的子组件上绑定fromchildmethod方法,对该方法进行监听,当该方法触发时,执行父组件中相应的方法fromchild。

          <template>
              <div class="parent-box">
                  <div>
                      <div>我是父页面</div>
                      <div style="font-size:12px;">{{message}}</div>
                      <div style="font-size:12px;color:red">{{fromchildmsg}}</div>
                  </div>
                  <children :message="tochildrenmsg" @fromchildmethod="fromchild"></children>
              </div>
          </template>
           
          <script>
          import children from './children.vue'
          export default {
              name:"parent",
              components:{
                  children
              },
              data(){
                  return {
                      message:'我是父页面的内容',
                      tochildrenmsg:'从父页面传过到子页面的内容',
                      fromchildmsg:''
                  }
              },
              methods:{
                  fromchild(){
                      this.fromchildmsg = '子页面触发的方法' //监听到子组件触发的方法,显示该内容
                  }
              }
          }
          </script>

          当点击子组件的对应的span,触发方法,向父组件进行通知。

          小结:父传子,props;子传父,this.$emit();触发、监听名称须一致。

          2、bus事件总线

          真实的场景中,组件不仅仅是“父子”关系,还有“兄弟”关系跟跨层级组件等等。这时候props跟$emit可能就不太适用了,这时候它出现了,那就是bus(事件总线),父子组件同样适用。

          bus之触发$emit、监听$on、关闭$off,主要用到的就是$emit跟$on。

          先在项目中新建一个文件夹bus,里面有个index.js文件,创建一个新的vue实例,然后导出模块。

          接下来import这个新的vue实例,也就是bus,常用的两种导入方式,一种是全局导入,另外一种是局部导入(需每个组件都导入一次)。以下为全局导入,在main.js里面将该bus作为当前vue实例的原型方法,能直接在各组件里面通过this.bus的方式调用。

          import vue from 'vue'
          import app from './app'
          import bus from './bus/index'
          vue.prototype.bus = bus
           
          new vue({
            el: '#app',
            components: { app },
            template: '<app/>'
          })

          下面展示实现bus通信过程,场景为父子,同样的,兄弟、跨层级用法与其类似:

          parent组件中向children组件通信,通过this.bus.$emit()触发

          <template>
              <div class="parent-box">
                  <div>
                      <div>我是父页面</div>
                      <div @click="tochildbus"><span>向子组件通信</span></div>
                  </div>
                  <children></children>
              </div>
          </template>
           
          <script>
          import children from './children.vue'
          export default {
              name:"parent",
              components:{
                  children
              },
              methods:{
                  tochildbus(){
                      let val = '父组件向子组件通信'
                      this.bus.$emit('tochild',val) //val为传过去的值,非必传
                  }
              }
          }
          </script>

          children组件监听parent组件触发的事件(在mounted阶段进行绑定监听),注意事件名称要一致,通过this.bus.$on()监听,当总线中监听到触发该方法,拿到传过来的值(也可以在里面执行自定义方法)。

          <template>
              <div class="children-box">
                  <div>
                      <div>我是子页面</div>
                      <div style="font-size:12px;color:blue;">{{fromparentmsg}}</div>
                  </div>
              </div>
          </template>
           
          <script>
          export default {
              name:"children",
              data(){
                  return {
                      fromparentmsg:''
                  }
              },
              mounted(){
                  this.bus.$off('tochild')
                  this.bus.$on('tochild',val=>{   
                      this.fromparentmsg = val    //此处为复制操作,也可在里面执行相应的方法
                  })
              }
          }
          </script>

          效果图:

           

          总结:父子,兄弟,跨级(祖孙等)通信写法相同,就不一一举例了,都是通过this.bus.$emit()触发,通过this.bus.$on()监听,执行相应的操作,切记:触发、监听名称必须相同!

          3、vuex状态管理库

          vuex相当于一个仓库,你可以往仓库里面放一些东西,保持存进去的时的状态,可以修改,也可以在需要的时候取出,是一个全局状态。本次只讲如何使用vuex进行通信,不深究其原理。

          安装vuex

          npm install vuex --save
          

          这里我新建一个文件夹,名称为store,里面有一个index.js文件,创建一个vuex.store实例,然后导出这个实例,从图中可以明确看出store的大致结构及其要素,具体不展开讲,关于vuex的相关文章数不胜数,可以自行去了解,这里主要讲大致用法。

           在mian.js全局引入,之后就可以直接使用了。

          import vue from 'vue'
          import app from './app'
          import router from './router'
          import bus from './bus/index'
          import store from './store/index'
           
          vue.config.productiontip = false
          vue.prototype.bus = bus
          new vue({
            el: '#app',
            router,
            store,
            components: { app },
            template: '<app/>'
          })

          方式一,this.$store.state.xxx,直接对state进行操作,在一个组件mounted阶段将值存如store中,当然也可在你想在的方法中进行操作。

          <template>
              <div class="parent-box">
                  <div>
                      <div>我是父页面</div>
                  </div>
                  <children></children>
              </div>
          </template>
           
          <script>
          import children from './children.vue'
          export default {
              name:"parent",
              components:{
                  children
              },
              data(){
                  return {
                      fromchildmsg:''
                  }
              }
              mounted(){
                  this.$store.state.msg = '父组件存入'    //在此处通过方式一存起来
              }
          }
          </script>

          其他组件从store中取出,当然同样也可以进行修改。

          <template>
              <div class="children-box">
                  <div>
                      <div>我是子页面</div>
                      <div @click="fromstore"><span>从store里面取</span></div>
                      <div>{{fromstoremsg}}</div>
                  </div>
              </div>
          </template>
           
          <script>
          export default {
              name:"children",
              data(){
                  return {
                      fromstoremsg:''
                  }
              },
              methods:{
                  fromstore(){
                      this.fromstoremsg = this.$store.state.msg
                  }
              }
          }
          </script>

          效果图:

            

           方式二,通过this.$store.getters.xxx、mapgetters进行取出。

          // store/index.js
          getters:{
              getmsg:state=>{
              return state.msg
            }
          },
           
           
          //组件中取
          this.$store.getters.getmsg
           
          //也可以用mapgetters的方式
          import { mapgetters } from 'vuex'
          computed: {
           ...mapgetters(['getmsg'])
          },

          对store存入数据该可以用mutations、actions(可异步)进行存入,具体就不展开了,有兴趣可以自己去深究。

           4、router

          可以通过动态路由、路由跳转方式进行传值,如this.$router.push({path:’xxx’,query:{value:’xxx’}}),在跳转的时候顺便传值,通过this.$route.params.value和this.$route.query.value获取到传过来的参数。该方式有局限性,只能在相互跳转的组件通信取值,且直接在跳转之后的页面进行刷新取不到值,视情况而用。

           5、缓存

           sessionstorage、localstorage、cookie

          多个组件之间的通信除了可以用bus、store之外,还比较一种常用的方式–缓存,在同一个窗口不关闭的情况下,该窗口下的其他组件都可以取到缓存中已经存好的值,利用sessionstorage.setitem(key,value)、localstorage.setitem(key,value)等将值存起来,其他组件可以通过sessionstorage.getitem(key)、localstorage.getitem(key)等方式拿到,多个页面共享缓存数据,刷新页面数据不会销毁,可以用sessionstorage.removeitem(key)、localstorage.removeitem(key)的方式将缓存移除,可用场景还是比较多的。

          总结:大致介绍vue组件中几种常用的通信、传值方式,考虑不同的场景使用不同的方式,提高开发效率,减少bug的产生。

          到此这篇关于vue实现组件间通信的几种方式(多种场景)的文章就介绍到这了,更多相关vue 组件通信内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!