vue父子通信的基本使用

项目中没怎么用过父子通信,很多页面都是路由切换实现的,后来做首页的时候发现首页的路径没法配置,我强行在原先的首页上写了个子组件,通过判断路径使其强行跳转实现的

这个时候跳转页面的时候就要使用到了父子间的通信问题了,首页点击详情,跳转详情页需要携带主播id。之前的做法是跳转的时候携带参数($router.push()方法),子组件显然不能这样用。

参考。看代码:

使用新脚手架举例:

父传值给子

helloworld.vue中

<template>    
   <section>
<!-- 路由跳转时$router.push()中可携带参数 (router/index.js中配置好路径即可)--> <router-link to="/child">路由跳转</router-link>
<!-- 父子组件传值使用自定义事件监听data值--> <childCom :message='passData'></childCom>
</setion> </template>
<script>
  import childCom from '@/components/childComponent'
  export default {
    data () {
      return {
        passData: 'this is parent's data !'
      }
    }
}
</script>

子组件childComponent.vue:

<template>
  <h4>这里是子组件</h4>
</template>
<script>
  export default {
    props: ['message'], // 接收父组件中的值
    data () {
      return {}
    },
    created() {
      console.log(this.message) // this is parent's data !
    }
  }
</script>

子组件传值到父组件(不能直接改变父组件中的值)

childComponent.vue

<template>
    <button @click="changeData"></button> // 点击事件触发
</template>
<script>
export default {
    data () {
        return {
            msg: 'This is child's component'
        }
    },
    methods: {
        changeData () {
             this.$emit('passMyData', this.msg) // emit触发自定义事件
        }
    }
}
</script>            

helloworld.vue

<childCom @passMyData="getData"></childCom> // 监听自定义事件,子组件触发之后,触发getData事件
methods: {
    getData (val) {
         console.log(val) // This is child's component 传值成功
}
}

 

posted @ 2018-10-18 17:09  ANEANE  阅读(518)  评论(0编辑  收藏  举报