vue组件,父组件与子组件之间通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangcc233/article/details/83549860

技术交流群:365814763

vue组件,组件是一个可复用的功能模块,即将具有相同功能的模块抽取成一个组件,在需要的地方引用即可,这体现了代码封装的思想,下面看一下组件是如何实现:
// 定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

组件是可复用的 Vue 实例,且带有一个名字:在这个例子中是 <button-counter>。我们可以在一个通过 new Vue 创建的 Vue 根实例中,把这个组件作为自定义元素来使用:

<div id="components-demo">
  <button-counter></button-counter>
</div>
如果使用webpack或者sublime工具开发时可以通过import组件,对组件的使用以及props组件传值。具体如下:
组件
<template>
    <div>我是一个组件</div>
</template>
<script type="text/javascript">
    export default {
        props: {//接收父组件传递的值
            father: [//参数名称
                type: Object//参数类型,有多种:Number等,具体参考api
            ]
        }
    };//暴露,让引用组件可以查找到
</script>
<style type="text/css"></style>
引用方式通过
import myComponents from '/子组件路径' 引用后即可在使用
<div>
  <myComponents :father="father"></myComponents>//:father为传递father给子组件
</div>

<script type="text/javascript">
    import myComponents from 'myComponents.vue'
    export default {
       components: {//在父组件中引用子组件
         myComponents//注册组件
       }
    }
</script>

而子组件与父组件之间通信,我们可以调用内建的 $emit 方法并传入事件的名字,来向父级组件触发一个事件,实例:
在子组件中:
<template>
    <div>我是一个组件</div>
    <div @click="click">向父组件发送消息</div>//这里也可以直接使用$emit('target')的方式向父组件传递消息
</template>
<script type="text/javascript">
    export default {
        methods: {
            click() {
                this.$emit('target');//使用$emit向父组件定义为target的目标中传递消息
            }
        }
    }
</script>

在父组件中:
<div>
  <myComponents @target="targetMethod"></myComponents>//targetMehod为在父组件中定义的方法,也可以是一个表达式
</div>
<script type="text/javascript">
    export default {
        methods: {
            targetMethod() {
                console.log('接受到子组件的消息')
            }
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/zhangcc233/article/details/83549860