• vue 组件传值 父子组件传值,兄弟组件传值


    父子组件中的传值

    父向子    v-bind props

     <!-- 组件使用v-bind传值 -->
     <router :msg="msg"></router>
    
    子组件:
    <p>子组件 ----- {{msg}}</p> 
    
     props: ["msg"], //props接收

     props:验证 

    props: {
        // fooA只接受数值类型的参数
        fooA: Number,
        // fooB可以接受字符串和数值类型的参数
        fooB: [String, Number],
        // fooC可以接受字符串类型的参数,并且这个参数必须传入
        msg: {
          type: String,
          required: true
        },
        // fooD接受数值类型的参数,如果不传入的话默认就是100
        fooD: {
          type: Number,
          default: 100
        },
        // fooE接受对象类型的参数
        fooE: {
          type: Object,
          // 当为对象类型设置默认值时必须使用函数返回
          default: function() {
            return { message: "Hello, world" };
          }
        },
        // fooF使用一个自定义的验证器
        fooF: {
          validator: function(value) {
            return value >= 0 && value <= 100;
          }
        },
      fooG: {
          type:Array,
          // 当为数组类型设置默认值时必须使用数组返回
          default: function() {
            return [];
          }
        },
    }

     props 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件修改父组件的状态。所以不应该在子组件中修改 props 中的值,Vue 警告。

    这是我上次想修改父组件的值遇到的报错:

     

    子向父  v-on $emit

    子组件:
    <button @click="cyy">按钮</button>
    methods: {
        cyy() {
          this.$emit("zifu", "子组件向父组件传值", true);
        }
      }
    
    父组件:
    <router  v-on:zifu="hehe"></router>
    methods: {
       hehe: function(data, data2) {
         console.log(data, data2);
       }
    }

    兄弟组件中的传值

    第一个办法:父组件中转

    <div> //爸爸A
        <router></router>    //哥哥A1
        <vuex></vuex>    //弟弟A2
    </div>

    A1要向A2传值 、 可以用$emit传给A、A在使用v-bind传给A2 

    使用父组件做中转 这里不举例了只是把上面的子向父,父向子连起来用

    第二个方法:Bus中央事件总线

    新建一个Bus.js 页面

    父组件组件代码:

    <div> //爸爸A
        <router></router>    //哥哥A1
        <vuex></vuex>    //弟弟A2
    </div>

     哥哥A1组件:

    <button @click="cyy">按钮</button> 点击按钮向弟弟A2传值
    脚本中:
    import Bus from "../api/Bus";   //注意引入
    export default {
      data() {
        return {
          a: 1
        };
      },
      methods: {
        cyy() {
          Bus.$emit("zifu", this.a++, "子组件向兄弟组件传值");    //存 Bus.$emit
        }
      }
    };

    弟弟A2组件:

    <p>接受兄弟A1传值=-------第{{ccc}}次,向{{ddd}}</p>
    脚本中:
    import Bus from "../api/Bus";
    export default {
      data() {
        return {
          ccc: "",
          ddd: ""
        };
      },
      created() {
        Bus.$on("zifu", (val, val1) => {    //取  Bus.$on
          this.ccc = val;
          this.ddd = val1;
        });
      }
    };

    传值就告一段落了~~~~~~~~~~~~by~~~

  • 相关阅读:
    Javascript小技巧
    VIM
    interview experience
    HTML5
    代码实践
    git clone 速度慢的解决办法
    vscode 找不到相对目录文件的解决办法
    python基础 13 类命名空间于对象、实例的命名空间,组合方法
    python 基础 12 初识类,类方法,类属性
    python 基础 11 带参数装饰器与递归函数
  • 原文地址:https://www.cnblogs.com/chen-yi-yi/p/11152391.html
Copyright © 2020-2023  润新知