学习Vue.js Day7

199 阅读1分钟

父子组件之间的通讯

顶层传递数据下来(大组件)=》(小组件)、

  • 通过props向子组件传递数据 (先定义后绑定)
  • 通过事件向父组件传递数据

props 两种写法

// 第一种写法通过数组,传递变量名
        // props:['cmovies', 'cmessage'],
        // 第二种写法
        props:{
          // 类型限制,
          cmovies: Array,
          // cmessage: String,
          // 提供默认值, 并且限制类型
          cmessage:{
            type: String,
            default: 'aaaaaa',
          }
        },

props中的组件中暂时不支持驼峰标识传递数据

若需要使用驼峰式时,需要使用 -来链接驼峰部分

<cpn :c-message="message" :c-info="info"></cpn>

解决以前的疑惑:模板中包含多个组件时,必须需要一个根div

子级向父级传递数据

自定义事件

  • 首先,通过$emit('自定义事件名')发射事件 tip:自定义事件名不要使用驼峰式
  • 父组件中通过 v-on:自定义事件名='父组件的事件名' 绑定子组件事件并且触发父组件事件
<div id="app">
  <h2>{{click.name}}被点击</h2>
  <cpn @item-click="cpnClick" :c-message="message" :c-info="info"></cpn>
</div>
<template id="cpn">
  <div>
    <button v-for="item in categories" @click="btnClick(item)">{{item.name}}</button>
    <h2>{{cMessage}}</h2>
    <h2>{{cInfo}}</h2>
  </div>
</template>
<script src="../js/vue.js"></script>
<script>
  // 1.子组件
  const cpn ={
    template:'#cpn',
    props:{
      cMessage:{
        type: String,
        default() {
          return 'aaaaaa';
        }
      },
      cInfo:{
        type:Array,
        default() {
          return [];
        }
      }
    },
    data(){
      return {
        categories: [
          {
            id:'1',
            name:'热门推荐',
          },
          {
            id:'2',
            name:'手机数码',
          },
          {
            id:'3',
            name:'电脑办公',
          },
        ]
      }
    },
    methods:{
      btnClick(item){
        // 传递数据给父组件, 发射一个事件
        this.$emit('item-click',item)
      }
    },
  }
  // 父组件
  const app = new Vue({
    el:'#app',
    data:{
      message: 'hello',
      info:[
        {
          name: 'jack',
          age: 18,
          height: 1.88,
        },
        {
          name: 'lucy',
          age: 18,
          height: 1.88,
        },
      ],
      click:{
        id: 1,
        name: '热门推荐',
      },
    },
    methods:{
      cpnClick(item) {
        this.click = item
      }
    },
    components:{
      cpn
    }
  })
</script>