组件通讯

组件是一个独立封闭的个体,不能直接使用外部的数据,组件可以为自己提供数据,通过 data(){return{msg:'...'} }

父组件到子组件 通过子组件 props: ['属性']

<body>
  <div id="app">
    <father class="father"></father>
  </div>
</body>
<script src="./vue.js"></script>
<script>
  // :skill="msg"自定义属性绑定动态数据
  //子组件通过 props: ['skill']获取skill属性的值
  //创建父组件
  Vue.component('father', {
    data() {
      return {
        msg: '好好学习,天天向上',
      }
    },
    template: `
  <div>
    <p>父对子说:{{msg}}</p>
  
    <son class='son' :skill="msg"></son>
  </div>
  `
  })
  //创建子组件
  Vue.component('son', {
    template: `
  <div>
    <p>子听父说:{{skill}}</p>
  </div>
  `,
    props: ['skill']
  })
  //一个Vue实例
  var vm = new Vue({
    el: '#app',
    data: {
    }
  })
</script>

子组件到父组件 this.$emit('方法', '数据')

<body>
  <div id="app">
    <father class="father"></father>
  </div>
</body>
<script src="./vue.js"></script>
<script>
  //创建父组件
  Vue.component('father', {
    data() {
      return {
        skill: ''
      }
    },
    template: `
  <div>
    <p>父听子说:{{skill}}</p>
  
    <son class='son' @fn='getSkill'></son>
  </div>
  `,
    methods: {
      // 父组件中提供一个方法
      getSkill(skill) {
        console.log(skill);
        // 参数skill就是子组件中传递过来的数据
        this.skill = skill
      }
    }
  })
  //创建子组件
  Vue.component('son', {
    data() {
      return {
        msg: '少喝酒,少抽烟,注意身体',
      }
    },
    template: `
  <div>
    <p>子对父说:{{msg}}</p>
  </div>
  `,
    created() {
      // 调用父组件中传递过来的方法,将数据作为参数传递
      // 第一个参数:表示要调用的方法名称
      // 第二个参数:表示传递父组件的数据
      this.$emit('fn', this.msg)
    }
  })
  //一个Vue实例
  var vm = new Vue({
    el: '#app',
    data: {
    }
  })
</script>

非父子组件之间的通讯   非父子组件之间通过一个空Vue实例来传递数据:const bus = new Vue()
  

<body>
  <div id="app">
    <box1 class="box1"></box1>
    <box2 class="box2"></box2>
  </div>
</body>
<script src="./vue.js"></script>
<script>
  // 非父子组件之间通过一个空Vue实例来传递数据:
  // bus 专业名称为:事件总线(公交车)
  const bus = new Vue()
  //创建组件
  Vue.component('box1', {
    data() {
      return {
        msg: 'I love you !!!'
      }
    },
    template: `
  <div>
    <p>这是box1组件,他说:{{ msg }}</p>
    <button @click='fn'>按钮</button>
  </div>
  `,
  methods:{
    fn() {
      //把数据传送到公共Vue实例上,参数一是bus的事件,参二是发出的数据
      bus.$emit('love', this.msg)
    }
  }
  })
  //创建组件
  Vue.component('box2', {
    data() {
      return {
        msg: ''
      }
    },
    template: `
  <div>
    <p>接受到box1的表白:{{ msg }}</p>
  </div>
  `,
    created() {
      //给bus注册事件,接收数据
      bus.$on('love', (data) => {
       console.log(data)
          this.msg = data
      })
    }
  })
  //一个Vue实例
  var vm = new Vue({
    el: '#app',
    data: {
    }
  })
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值