vue.js学习笔记(4)— 父子组件之间通信的第一种方式 props 和 $emit

我们知道,vue组件中,父组件把数组传递给子组件的话,通常是使用props传递,而vue规定,prop是只能单向下行传递的,那么子组件要怎么才能实现数据的向上传递呢,这里引述一个概念:"父子组件的关系:prop向下传递,事件向上传递",上一篇文章当中,关于数据向上传递用到的事件方法 $emit() 也进行了详细的说明,不懂的童鞋可以翻回去看一下。下面就是今天要说的父子组件相互通信的问题,点击效果依次如下:

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>session</title>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
        <style type="text/css">
            #session {
                width: 600px;
                margin: 0 auto;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="message-event-example" class="demo">
          <blog-post post-title="hello!" @father="handleMessage"></blog-post>
        </div>
        
        <script>
            Vue.component('blog-post', {
                props: ['postTitle'],
                template: '<h3 v-on:click="takeMe">{{ postTitle }},点我啊</h3>',
                data:function(){
                      return {
                          message:this.postTitle
                      }
                },
                methods:{
                      takeMe:function () {
                          alert("我是子组件");
                          this.$emit("father",{message:this.message})
                      }
                }
            })
            
            new Vue({
                el: '#message-event-example',
                data: {
                    messages: []
                },
                methods: {
                    handleMessage: function (payload) {
                        alert("我是父组件",payload.message);
                    }
                }
            })
        </script>
    </body>
</html>

下面就介绍下为什么父组件当中要这样写:

  1. 我们要知道,组件要在vue实例初始化之前注册好
  2. 组件也是有大部分vue实例的功能的
  3. 组件当中data一定要写成函数的形式
  4. html只能识别小写字母,所以驼峰命名法要改成小写加短杠的形式(kebab-case)

所以呢,我们为了把接收父组件的向下传递来的信息,表现的更明显一些,在组件当中的data函数里,创建了一个属性message,用来保存传递下来的数据,然后通过事件 $emit 把数据通过 alert 的形式打印出来,方便直观理解感受,怎么样(⊙_⊙),是不是理解了父子组件相互通信的机制了。

猜你喜欢

转载自www.cnblogs.com/zxn-9588/p/8970573.html