1. 程式人生 > >vue 中父子組件傳值:props和$emit

vue 中父子組件傳值:props和$emit

port 參數 cti 組件 code lan func ssa app

1 父組件向子組件傳值:通過props數組:

//父組件 App.vue
<template>
  <div id="app">
    <hello mes-father="爸爸無可奉告"></hello>
  </div>
</template>
//子組件Hello.vue
<template>
  <div class="hello">
    <p>{{mesFather}}</p>
  </div>
</template>

<script>
export 
default { props:[‘mesFather‘] } </script>

子組件即可收到通信

傳進來的數據是mes-father, vue轉化成mesFather, 在js 裏面寫mesFather

2 子組件向父組件傳值:自定義事件

子組件:

<template>
  <div class="hello">
    <!-- 添加一個input輸入框 添加keypress事件-->
    <input type="text" v-model="inputValue" @keypress.enter="enter">
    <p>{{mesFather}}</p>
  </div>
</template>

<script>
export 
default { props:[‘mesFather‘], // 添加data, 用戶輸入綁定到inputValue變量,從而獲取用戶輸入 data: function () { return { inputValue: ‘‘ } }, methods: { enter () { this.$emit("sendiptVal", this.inputValue) //子組件發射自定義事件sendiptVal 並攜帶要傳遞給父組件的值, // 如果要傳遞給父組件很多值,這些值要作為參數依次列出 如 this.$emit(‘valueUp‘, this.inputValue, this.mesFather);
} } } </script>

父組件:

<template>
  <div id="app">
    <img src="./assets/logo.png">

    <!-- 添加自定義事件valueUp -->
    <hello mes-father="message from father" @valueUp="recieve"></hello>

    <!-- p元素,用於展示子組件傳遞過來的數據 -->
    <p>子組件傳遞過來的數據 {{childMes}}</p>
  </div>
</template>

<script>
import Hello from ‘./components/Hello‘

export default {
  name: ‘app‘,
  components: {
    Hello
  },
  // 添加data
  data: function () {
    return {
      childMes:‘‘
    }
  },

  // 添加methods,自定義事件valueUp的事件處理函數recieve
  methods: {
    recieve: function(mes) { // recieve 事件需要設置參數,這些參數就是子組件傳遞過來的數據,因此,參數的個數,也要和子元素傳遞過來的一致。
      this.childMes = mes;
    }
  }
}
</script>

vue 中父子組件傳值:props和$emit