vue2.0父子组件间传递数据

关于父子组件之间传递数据其实文档上都说得很明白。
但是如果完全不懂的人做计也看不懂,下面是一个小例子,有两个文件
1.parent.vue

<template>
  <child :child-msg="msg" @ok="event"></child>
</template>

<script>
import child from './child.vue';
export default {
  data(){
    return{
      msg:'hello worldgogo'
    }
  },
  components:{
    child
  },
  methods:{
    event(val){
        console.log(val);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

2.child.vue

<template>
    <p>{{childMsghello}}</p>
</template>

<script>
export default {
    props: ['childMsg'],
    data(){
        return{
            childMsghello:this.childMsg+'this is child'
        }
    },
    created(){
        //自定义事件,并且给监听此事件的回调函数的值设为200
        this.$emit('ok','200');
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

路由啥的就自己配吧。这都不会就凉了。。。。。。然后就可以看看文档

Vue2.0中,父子组件可以通过props属性和$emit方法进行函数的传递。 首先,在父组件中,通过props属性将函数传递给子组件。在父组件中定义一个函数,然后将它添加到子组件的props中。例如: ```js // 父组件 <template> <div> <child-component :childFunction="parentFunction"></child-component> </div> </template> <script> export default { methods: { parentFunction() { // 在父组件中定义的函数 } } } </script> ``` 然后,在子组件中,通过this.$emit方法将其作为事件,从而调用父组件中的函数。在子组件中通过$emit方法触发一个事件,并将需要传递的参数传递给父组件中的函数。例如: ```js // 子组件 <template> <div> <button @click="childFunction">点击按钮</button> </div> </template> <script> export default { props: { childFunction: { type: Function, required: true } }, methods: { childFunction() { this.$emit('child-function'); } } } </script> ``` 最后,在父组件中,监听子组件的事件,并调用相应的处理函数。在父组件中通过v-on指令监听子组件触发的事件,并在相应的处理函数中调用父组件本身的函数。例如: ```js // 父组件 <template> <div> <child-component :childFunction="parentFunction" @child-function="handleChildFunction"></child-component> </div> </template> <script> export default { methods: { parentFunction() { // 在父组件中定义的函数 }, handleChildFunction() { // 处理子组件触发的事件 } } } </script> ``` 通过上述的方式,就可以在Vue2.0中实现父子组件的函数传递。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值