zoukankan      html  css  js  c++  java
  • vue 组件之间的通讯方式

    一、父到子

      1. 通过props属性

       父级页面

    <child-template :msg="name"></child-template>

       子级页面

    props: {
         msg: String   
    }
    或
    props: {
        msg: {
            type: String,
            default: "默认值"
        }
    }

       2. 通过refs (父获取子)

         父页面

    <child-template ref="childs"></child-template>

         此时父页面可以通过this.$refs.childs.xxx来获取子页面的属性,并修改。

      (注:通过this.$refs获取子组件的属性或方法需要子组件加载完成,及需要在父组件的mouted中获取。之后会子父组件加载顺序

      3. 通过$children(父获取子)

    this.$children[0].xxx

      注:通过$children获取子组件属性不保证顺序,官方不建议使用

    二、子到父

      1. 通过$emit()

       父组件

    <child-template @方法名="函数"></child-template>

      注:方法名为子组件通过$emit() 广播出来的方法名

       子组件

    this.$emit("方法名", "参数")

      2. 通过$parent  (子获取父)

    this.$parent.xxx

      注:以上写法是获取当前一级父级的属性或方法

    三、兄弟组件通信   

      通过共同的祖辈搭桥,找到相同的$parent或$root。

    // brother1
    this.$parent.$on("方法名", "参数");
    
    // brother2
    this.$parent.$emit("方法名");

    四、祖先和后代之间通信。

      使用provide/inject 和data,methods同级。官方不建议子父之间的使用,用户写插件时隔代传参

    // 祖代
    provide(){
      return {showMsg: "11"}
    }
    
    //后代
    inject:["showMsg"]
    provide也可以返回一个函数
    // 祖代
    provide() {
      return {
        showMsg: this.fn
      }  
    }
    
    // 后代
    inject: ["showMsg"]

    五、任意两个组件之间,使用事件总线bus或者vuex。

      1. 事件总线($bus)

      在main.js中

    Vue.prototype.$bus = new Vue()
    

      子组件

    this.$bus.$emit("方法名", "参数")
    

      父组件 此方法放到mouted中(在父级的mouted之后子组件才加载完成)

    this.$bus.$on("方法名",(参数) => {})
    

      2. 通过vuex

  • 相关阅读:
    1004 Counting Leaves
    1003 Emergency (25分)
    1002 A+B for Polynomials (25分)
    1001 A+B Format
    Weekly Contest 139
    491. Increasing Subsequences
    488. Zuma Game
    servlet总结
    firefox插件Firebug的使用教程
    KMP---POJ 3461 Oulipo
  • 原文地址:https://www.cnblogs.com/little-baby/p/14514010.html
Copyright © 2011-2022 走看看