vue父子组件相互传值

2018-11-07  本文已影响0人  苏码码

一、父组件向子组件传值


屏幕快照 2018-11-07 上午10.05.59.png

1、父组件:

<template>
  <div class="father">
    <h1>父组件子组件相互传值</h1>
    <h5>简单 / 易用 / 便捷</h5>
    <h5>1:父组件向子组件传值</h5>
    <div><span>父组件:</span><input type="text" v-model="inputValue"></div>
    <child :fromFather="inputValue"></child>

  </div>
</template>

<script>
//引入子组件
import Child from '../components/Child.vue'
export default {
  name: 'Father',
  components:{
    'child':Child
  },
  data () {
    return {
      inputValue:''
    }
  }
}
</script>

2、子组件:

<template>
  <div class="child">

    <!-- 父组件向子组件传值-子组件接收值 -->
    <div><span>子组件:{{fromFather}}</span></div>

  </div>
</template>

<script>
export default {
  name: 'Child',
  props:{
    fromFather: String,//在父组件中接收值
    required: true
  },
  data () {
    return {

    }
  }
}
</script>

二、子组件向父组件传值


屏幕快照 2018-11-07 上午10.06.42.png

1、父组件

<template>
  <div class="father">
    <h1>父组件子组件相互传值</h1>
    <h5>简单 / 易用 / 便捷</h5>

    <h5>2:子组件向父组件传值</h5>
    <div><span>父组件:{{fromChild}}</span></div>
    <child v-on:fromChildValue="fromChildValueAction"></child>

  </div>
</template>

<script>
//引入子组件
import Child from '../components/Child.vue'
export default {
  name: 'Father',
  components:{
    'child':Child
  },
  data () {
    return {
      fromChild:''
    }
  },
  methods:{
    // 子组件传过来的值
    fromChildValueAction(text){
      this.fromChild = text
    }
  }
}
</script>

2、子组件:

<template>
  <div class="child">
    
    <!-- 子组件向父组件传值 -->
    <div><span>子组件:</span><button v-on:click="childValueAction">提交</button></div> 

  </div>
</template>

<script>
export default {
  name: 'Child',
  data () {
    return {
      childValue:'我是子组件中的值'
    }
  },
  methods:{
    childValueAction(){
      // 第一个参数fromChildValue是父组件v-on的监听方法
      this.$emit('fromChildValue',this.childValue)
    }
  }
}
</script>

详情代码地址见:https://github.com/zzsuyifeng/transfer-value

上一篇 下一篇

猜你喜欢

热点阅读