vue.js學習筆記(4)— 父子組件之間通訊的第一種方式 props 和 $emit

咱們知道,vue組件中,父組件把數組傳遞給子組件的話,一般是使用props傳遞,而vue規定,prop是隻能單向下行傳遞的,那麼子組件要怎麼才能實現數據的向上傳遞呢,這裏引述一個概念:"父子組件的關係:prop向下傳遞,事件向上傳遞",上一篇文章當中,關於數據向上傳遞用到的事件方法 $emit() 也進行了詳細的說明,不懂的童鞋能夠翻回去看一下。下面就是今天要說的父子組件相互通訊的問題,點擊效果依次以下:css

代碼以下:html

<!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>

下面就介紹下爲何父組件當中要這樣寫:vue

  1. 咱們要知道,組件要在vue實例初始化以前註冊好
  2. 組件也是有大部分vue實例的功能的
  3. 組件當中data必定要寫成函數的形式
  4. html只能識別小寫字母,因此駝峯命名法要改爲小寫加短槓的形式(kebab-case)

因此呢,咱們爲了把接收父組件的向下傳遞來的信息,表現的更明顯一些,在組件當中的data函數裏,建立了一個屬性message,用來保存傳遞下來的數據,而後經過事件 $emit 把數據經過 alert 的形式打印出來,方便直觀理解感覺,怎麼樣(⊙_⊙),是否是理解了父子組件相互通訊的機制了。chrome

相關文章
相關標籤/搜索