vue 组件通信

本文主要解决vue组件之间的通信问题

Prop 向下传递,事件向上传递

Prop

(主要用于父组件向子组件下发数据)

  1. 子组件中显式地用 props选项声明它预期的数据:
// 子组件使用数据
首页

// props声明
export default {
  data() { ... },
  props: ['navActive', 'isZjrc']
  ...
}
  1. 父组件中传入数据
// 传入静态数据


// 传入动态值

事件

(主要用于子组件给父组件发送数据)

父子组件通信

  1. 在子组件中触发父组件的事件


...
export default {
  data() { ... },
  methods: {
       toParent() {
          this.$emit('childToParentMsg', '子组件向父组件传值')
       }
  }
}

  1. 在父组件中监听事件

{{childMsg}}

// 事件绑定 export default { data() { return { childMsg: '' } }, components: { HeaderNav }, methods: { showMsg(msg) { this.childMsg = msg } } }

非父子组件通信

  1. 在组件A中监听事件
export default {
    mounted() {
        this.$on("showDialog", id => {
          this.showDialog(id);
        });
    }
}
  1. 在组件B中触发A的事件


export default {
    mounted() {
        this.$refs["invoiceDialog"].$emit("showDialog",this.customerId);
    }
}

你可能感兴趣的:(vue 组件通信)