vue2 $listeners和$bus,$attrs

$listeners父传子和子改父

$bus组件共享参数

父组件里

<helloworld @msg="msg" @send="send" :name="name"></helloworld>
import helloworld from "../components/HelloWorld";
  //注册组件
  components: {
    helloworld
  },
  // 定义变量
  data() {
    return {
      msg: "父组件的值",
      far: "父组件"
    };
  },
   //事件方法执行
  methods: {
    send(val) {
      this.msg = val;
    }
  },
  //页面初始化方法
  mounted() {
    this.$bus.$on("goto", data => {
      this.far = data;
    });
  },

子组件里

<button @click="update">改变父组件的值</button>
 //接收父组件传递过来的参数
  props: {//未接收name},
 // 定义变量
  data() {
    return {
      content: "子组件的值",
      cont: "改变之后"
    };
  },
  //事件方法执行
  methods: {
    update() {
      //console.log(this.$listeners);
      this.$listeners.send(this.content);//给父组件send事件传递参数
      this.$bus.$emit("goto", this.cont);//分发goto事件
    }
  },
  //页面初始化方法
  mounted() {
    console.log(this.$listeners.msg.fns); //接收父组件传过来的值
    console.log(this.$attrs)//接收非prpos接收的参数(打印name)
  },

版权声明:本文为weixin_49295874原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。