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

更新-----------vue

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

 

在vue-cli Login.vue父組件中有AcceptAndRefuse.vue子組件,首先import進子組件hello,而後在components中註冊組件,而後在template中使用<hello></hello>組件,制定msg信息vue-cli

//父組件 App.vue
<template>
<div id="app">
<!-- the router outlet, where all matched components would ber viewed -->
<router-link v-bind:to="'/'">Home</router-link>
<!-- 爲咱們建立兩個錨點標籤,並動態路由,使頁面不須要從新加載-->

<router-link v-bind:to="'/about'">About</router-link>
<router-view></router-view>
<hello msg-father="dad無可奉告"></hello>
</div>
</template>

<script>
import hello from './components/hello'
export default {
name: 'app',
components:{
hello
}
}
</script>
<!-- styling for the component -->
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
//子組件./components/Hello.vue
//經過props接收信息
<template>
<div class="hello">
<p>{{msgFather}}</p>
</div>
</template>

<script>
export default {
name: 'hello',
data () {
return {
}
},
props:['msgFather']
}
</script>

<style scoped>

</style>

子組件便可收到通訊數組

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

http://www.jianshu.com/p/2670ca096cf8this

2 子組件向父組件傳值:自定義事件,this.$emit,發送信息,在父組件中spa

子組件:code

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

<script>
export default {
  props:['mes'],

  // 添加data, 用戶輸入綁定到inputValue變量,從而獲取用戶輸入
  data: function () {
    return {
      inputValue: ''  
    }
  },
  methods: {
    enter () {
      this.$emit("sendiptVal", this.inputValue) 
      //子組件發射自定義事件sendiptVal 並攜帶要傳遞給父組件的值,
      // 若是要傳遞給父組件不少值,這些值要做爲參數依次列出 如 this.$emit('valueUp', this.inputValue, this.mesFather); 
    }
  }
}
</script>

父組件:component

<template>
  <div>
    <p> father</p>
      <accept-and-refuse :mes=loginJson.animal  @sendiptVal='showChildMsg'></accept-and-refuse>
  </div>

</template>

<script>
import AcceptAndRefuse from '@/components/public/AcceptAndRefuse'
    
export default {
  data() {
    return {

      message:'hello message',
      loginJson:{
          "animal":"dog"
      }

  },
  mounted(){

  },
  methods: {
  components:{
    AcceptAndRefuse
      
  }
}
</script>

<style>

</style>

 在vue組件中,import子組件,components中註冊,template中使用,router跳轉router

相關文章
相關標籤/搜索