本文实例讲述了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>
参考:https://jingyan.baidu.com/article/455a99505b639da1662778e1.html
希望本文所述对大家vue.js程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
2020-07-21 html5如何监听veido的全屏 + css的字体间距 + JS的window.open() + 软技能svn与git
html+css+js适合前端小白的实战全解(超详细)——2048小游戏(二)
在使用@angular/cli创建的angular项目上添加postcss等一系列移动端自适应插件
网友评论