vuejs中父子组件之间通信

vuejs中父子组件之间通信

一、父组件向子组件传递消息

// Parent.vue

<template>
  <div class="parent">
    <v-child :msg="message"></v-child>
  </div>
</template>
<script>
  import VChild from './child.vue'
  export default {
    components: {
      VChild
    },
    data () {
      return {
        // 父组件将message作为参数传入子组件中
        message: '来自父组件消息'
      }
    }
  }
</script>
// Child.vue

<template>
  <div class="child">
    <h1>child</h1>
    <p>{{ msg }}</p>
  </div>
</template>
<script>
  export default {
    // 通过props定义外部系统可以传入的参数
    // 定义了一个msg变量,类型是String,默认是空字符串
    props: {
      msg: {
        type: String,
        default: ""
      }
    }
  }
</script>
// router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Parent from '@/test/Parent'


Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/parent',
      component: Parent
    }
  ]
})

二、子组件向父组件传递消息

// Parent.vue

<template>
  <div class="parent">
    <v-child :msg="message" @childNotify="childNotify"></v-child>
  </div>
</template>
<script>
  import VChild from './child.vue'
  export default {
    components: {
      VChild
    },
    data () {
      return {
        // 父组件将message作为参数传入子组件中
        message: '来自父组件消息'
      }
    },
    methods: {
      childNotify (params) {
        console.log(params)
      }
    }
  }
</script>
// Child.vue

<template>
  <div class="child" @click="notifyParent">
    <h1>child</h1>
    <p>{{ msg }}</p>
  </div>
</template>
<script>
  export default {
    // 通过props定义外部系统可以传入的参数
    // 定义了一个msg变量,类型是String,默认是空字符串
    props: {
      msg: {
        type: String,
        default: ""
      }
    },
    methods: {
      notifyParent () {
        var params = {
          m: 1,
          n: 2
        }
        // 子组件以事件的形式通知父组件(需要使用$emit方法,第一个参数,事件名称;第二个事件附带的参数)
        this.$emit('childNotify', params)
      }
    }
  }
</script>

vuejs如何实现父子组件之间通信
源代码:源代码下载

猜你喜欢

转载自blog.csdn.net/qq_25479327/article/details/81022339