Vue学习-父子组件通信

父子组件通信

1. 父传子props


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  <div id="app">
    <cpn v-bind:cmovies="movies">cpn>
  div>
  <template id="cpn">
    <div>
      <ul>
        <li v-for="item in cmovies">{{item}}li>
      ul>
    div>
  template>
  <script src="../js/vue.js">
  script>
  <script>
    //父传子: props
    const cpn = {
      template: '#cpn',
      // props:['cmovies'],
      props: {
        // cmovies: Array,
        cmovies: {
          type: Array,
          default(){
            return []
          },
          required: true,
        },
      },
      data() {
        return {
          
        }
      },
    }
    const app = new Vue({
      el: '#app',
      data: {
        message: 'hello',
        movies: ['海王','QT','FCLC'],
      },
      components: {
        cpn
      }
    })
  script>
body>
html>

v-bind不支持驼峰:HTML不区分大小写

子传父:自定义事件


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  <div id="app">
    <cpn @btnclick="cpnClick">cpn>
  div>
  <template id="cpn">
    <div>
      <ul>
        <li v-for="item in categories" @click="itemClick(item)"><button>{{item.name}}button>li>
      ul>
    div>
  template>
  <script src="../js/vue.js">
  script>
  <script>
    const cpn = {
      template: '#cpn',
      
      data() {
        return {
          categories: [
            {id:'a',name:'热门推荐'},
            {id:'b',name:'手机数码'},
            {id:'c',name:'家用电器'},
            {id:'d',name:'电脑办公'},
          ]
        }
      },
      methods: {
        itemClick(item){
          this.$emit('btnclick',item);
        }
      },
    }
    const app = new Vue({
      el: '#app',
      data: {
        message: 'hello',
        movies: ['海王','QT','FCLC'],
      },
      components: {
        cpn
      },
      methods: {
        cpnClick(item){
          console.log(item.name);
        },
      },
    })
  script>
body>
html>

你可能感兴趣的:(Vue学习-父子组件通信)