首页 > 其他 > 详细

vue 父子组件、兄弟组件传值

时间:2018-09-26 11:20:04      阅读:173      评论:0      收藏:0      [点我收藏+]

(一)父组件给子组件传值,关键字:props

 父组件:

<template>
  <div>
    <h1>父组件</h1>
  <!-- 引入子组件 --> <child :sendMsg="fatherMsg"></child> </div> </template> <script> import child from ‘@/components/child‘ export default { name: ‘father‘, components: { child }, data() { return { fatherMsg: ‘嗨,儿子‘ // 传递给子组件的值 } } } </script>

子组件:通过props拿到父组件传递过来的值

<template>
  <div>
    <h1>子组件</h1>
    <span>获取父组件传值:{{sendMsg}}</span> 
  </div>
</template>

<script>
export default {
  name: ‘child‘,
  data() {
    return {

    }
  },
  props: [‘sendMsg‘] // 拿到父组件绑定到sendMsg的值,然后在子组件下显示出来
}
</script>

 

(二)子组件给父组件传值:通过触发事件传递值

以上面的示例代码作为基础修改,子组件:

<template>
  <div>
    <h1>子组件</h1>
    <span>获取父组件传值:{{sendMsg}}</span><hr>
    <button @click="sendToFather">子组件给父组件传值</button>
  </div>
</template>

<script>
export default {
  name: ‘child‘,
  data() {
    return {
      childMsg: ‘这是来自子组件的数据‘
    }
  },
  props: [‘sendMsg‘],
  methods: {
    sendToFather: function() {
      this.$emit(‘getChildValue‘, this.childMsg); // 参数1 getChildValue作为中间状态,参数2 this.childMsg即为传递给父组件的数据
    }
  }
}
</script>

 

父组件:

<template>
  <div>
    <h1>父组件</h1>
    <!-- 引入子组件 定义一个on的方法监听子组件的状态,然后通过getChild方法获取子组件传递的数据-->
    <child :sendMsg="fatherMsg" v-on:getChildValue="getChild"></child>
    <span>这是来自子组件的数据:{{childValue}}</span>
  </div>
</template>

<script>
import child from ‘@/components/child‘
export default {
  name: ‘father‘,
  components: {
    child
  },
  data() {
    return {
      fatherMsg: ‘嗨,儿子‘,
      childValue: ‘‘
    }
  },
  methods: {
    getChild: function(data) { // 此时的参数data为子组件传递的值,即this.$emit()的第二个参数
      this.childValue = data;
    }
  }
}
</script>

 

(三)同级组件传递数据

对于同级组件传值用的较多的情况,推荐直接使用vuex进行状态管理会比较方便。

vue 父子组件、兄弟组件传值

原文:https://www.cnblogs.com/secretAngel/p/9705809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!