天天看点

Vue组件之间常见的三种传值方式

Vue组件之间的传值方式

  • 父传子

    方法:父组件内设置要传的数据,在父组件中引用的子组件上绑定一个自定义属性并把数据绑定在自定义属性上,在子组件添加参数props接收即可。具体可参考官方文档。

  • 子传父

    方法:子组件通过vue实例方法$emit进行触发并且可以携带参数,父组件监听使用@(v-on)进行监听,然后进行方法处理。

  • 非父与子之间的传值
    1. 第一种:eventbus

      Event BUS总线方法:通过新建一个vue实例,来实现 o n 接 收 和 on接收和 on接收和emit 来触发事件

      创建eventBus.js:

      export default (Vue) => {
        const eventBus = new Vue();
        Vue.prototype.$bus = {
          $on (...param) {
            eventBus.$on(...param);
          },
          $off (...param) {
            eventBus.$off(...param);
          },
          $once (...param) {
            eventBus.$once(...param);
          },
          $emit (...param) {
            eventBus.$emit(...param);
          }
        }
      }
                 
      在main.js引用并调用:
      import EventBus from './eventBus';
      EventBus(Vue); //传参为Vue注册全局事件
                 
      在一组件发送事件:
      func(){
      	this.$bus.$emit("函数名funcName","参数args");
      }
                 
      在另一组件接受事件:
      func(){
      	this.$bus.$on("函数名funcName",(args) => {
      		//todo
      	});
      }
                 
    2. 第二种:状态管理vuex

      借组vux插件实现组件之间的传值。

      在store.js中创建一个store实例对象

      const store = new Vuex.Store({
        // ...
        strict: process.env.NODE_ENV !== 'production';
        state () {
          return {
            count: 0
          }
        },
        mutations: {
          increment (state) {
            state.count++
          }
        },
        actions: {
          increment ({ commit }) {
            commit('increment')
          }
        }
        // module 和 getter 等等...
      })
                 

      更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

      你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

      Action 类似于 mutation,不同在于:

      - Action 提交的是 mutation,而不是直接变更状态。
        - Action 可以包含任意异步操作。
                 

      Action 通过 store.dispatch 方法触发:

      帅哥美女们,如果觉得好的话!动动手点个赞哦,么么哒!

继续阅读