Vue - 组件通信

单层组件通信
Prop
组件实例的作用域是孤立的。这意味着不能 (也不应该) 在子组件的模板内直接引用父组件
的数据。父组件的数据需要通过 prop 才能下发到子组件中。

子组件要显式地用 props 选项声明它预期的数据

Vue.component('child', {
  // 声明 props
  props: ['message'],
  // 就像 data 一样,prop 也可以在模板中使用
  // 同样也可以在 vm 实例中通过 this.message 来使用
  template: '<span>{{ message }}</span>'
})

然后给他传一个消息

<child message="hello!"></child>
props
props 可以是数组或对象,用于接收来自父组件的数据。props 可以是简单的数组,或者
使用对象作为替代,对象允许配置高级选项,如类型检测、自定义校验和设置默认值
// 简单语法
Vue.component('props-demo-simple', {
  props: ['size', 'myMessage']
})

// 对象语法,提供校验
Vue.component('props-demo-advanced', {
  props: {
    // 检测类型
    height: Number,
    // 检测类型 + 其他验证
    age: {
      type: Number,
      default: 0,
      required: true,
      validator: function (value) {
        return value >= 0
      }
    }
  }
})

照着敲得例子

// 组件
<template id="my_div">
  <div>
    <h1>{{msg}}</h1>
    <img :src="imgsrc" alt="" width="200px">
  </div>
</template>

<script src="js/vue.js"></script>
<script>
// 1. 创建组件
Vue.component('my-div',{
  template: '#my_div',
  // vue不支持驼峰???
  props: ['msg', 'imgsrc']
});
new Vue({
  el: '#app',
  data: {

  }
});
// 传入消息
<div id="app">
    <my-div msg="今天要下雨" imgsrc="img/123.jpg"></my-div>
</div>

效果图


多层组件通信
具体实例

模板

<template id="my_img">
  <div>
    <img :src="imgsrc" width="200px" alt="">
  </div>
</template>

<template id="my_title">
  <div>
    <h2>{{title}}</h2>
  </div>
</template>

<template id="my_parent">
  <div>
    <!--动态绑定-->
    <child2 :title="imgtitle"></child2>
    <child1 :imgsrc="imgsrc"></child1>
  </div>
</template>

注册

<script src="js/vue.js"></script>
<script>
  // 子组件的实例
  let Child1 = Vue.extend({
    template: '#my_img',
    props: ['imgsrc']
  });
  let Child2 = Vue.extend({
    template: '#my_title',
    props: ['title']
  });
  Vue.component('my-parent', {
    props: ['imgtitle', 'imgsrc'],
    components: {
      'child1': Child1,
      'child2': Child2
    },
    template: '#my_parent'
  });
  new Vue({
    el: '#app',
    data: {
      title: '卧槽?!',
      img: 'img/123.jpg'
    }
  });
</script>

调用传消息

<div id="app">
  <!--动态绑定-->
  <my-parent :imgtitle="title" :imgsrc="img"></my-parent>
</div>

效果图
每个框就是个组件

猜你喜欢

转载自blog.csdn.net/qq_38265784/article/details/80037352