vue组件通信

父传子数据

  • 子组件在props里面定义一个数组
  • 父组件通过绑定子组件中props的值,来进行传递数据
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
    {{message}}
  <cpn :cmovies="movies"></cpn>
</div>
<script src="../vue.js"></script>
<template id="cpn">
  <div>
    {{cmovies}}
  </div>
</template>
<script>
  // 父传子数据通过props传递
  const cpn = {
    template: '#cpn',
    props: ['cmovies',],
  }
  
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
      movies: ['海贼王','海王','天下无紫萼']
    },
    components: {
      cpn
    }
  })
</script>
</body>
</html>

子传父通信

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
    {{message}}
  <cpn @cpnup="getcpn"></cpn>
</div>
<script src="../vue.js"></script>
<template id="cpn">
  <div>
    <button v-for="item in categeries" @click="cpnclick(item)">{{item.name}}</button>
  </div>
</template>
<script>
  const cpn = {
    template: '#cpn',
    data() {
      return {
        categeries: [
          {id:1,name:'手机'},
          {id:2,name:'电脑'},
          {id:3,name:'电视机'},
          {id:4,name:'空调'},
        ]
      }
    },
    methods: {
      cpnclick(item){
        console.log(item)
        this.$emit('cpnup',item)
      }
    }

  }

  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',

    },
    components: {
      cpn
    },
    methods: {
      getcpn(item) {
        console.log('aaaaa',item)
      }
    }
  })
</script>
</body>
</html>
posted @ 2021-06-02 20:30  竹石2020  阅读(30)  评论(0编辑  收藏  举报