vuejs中父子组件之间通信方法实例详解

// Parent.vue <template> <div> <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> <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: 'https://www.jb51.net/', name: 'HelloWorld', component: HelloWorld }, { path: '/parent', component: Parent } ] })

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

// Parent.vue <template> <div> <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 @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>

参考:https://jingyan.baidu.com/article/455a99505b639da1662778e1.html

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/92e20d0759e31732589a122cf635a147.html