首页 > 语言 > JavaScript > 正文

vue组件间通信解析

2024-05-06 15:10:30
字体:
来源:转载
供稿:网友

组件间通信(父子,兄弟)

相关链接/组件通信:点击查看

学习链接:Vue.js——60分钟快速入门点击查看

分分钟玩转Vue.js组件点击查看

父组件传子组件

父传子方法(一) 属性传递 props

//子组件<template>  <ul> <li v-for="item in dataList">{{item}}</li> </ul> </template><script> export default {  props : { dataList : [] } }</script>
//父组件<template> <component-child v-bind:data-list="dataList"> </component-child>  <input v-model="dataInput" v-on:keyup.13="addDataItem()" ></input></template><script>import ComponentChild from './child.vue'export default {  data () {  return {  dataInput: "",  dataList : [ 'hello world!','welcome to use vue.js' ]  }  },  components : { ComponentChild },  methods : {  addDataItem () {  let self = this  if( !(self.dataInput && self.dataInput.length > 0) ) { return }  self.dataList.push( self.dataInput )  self.dataInput = ""  }  }}</script>

父传子方法(二) 广播事件传递 vm.$broadcast

//子组件<template>  <ul>  <li v-for="item in dataList">{{item}}</li>  </ul> </template><script>export default {  data () {  return {  dataList : [ 'hello world!', 'welcome to use vue.js' ]  }  },  events : {  addChildDataEvent : function ( dataInput ) {  this.dataList.push( dataInput )  }  }}</script>
//父组件<template>  <component-child></component-child>  <input v-model="dataInput" v-on:keyup.13="addDataItem()" ></input></template><script> import ComponentChild from './child.vue' export default {  data () {  return { dataInput: "" }  },  components : { ComponentChild },  methods : {  addDataItem () {  let self = this  if( !(self.dataInput && self.dataInput.length > 0) ) { return }  //广播到子组件  self.$broadcast( 'addChildDataEvent', self.dataInput )  self.dataInput = "" }  } }</script>

子组件传父组件

子传父方法 派遣事件传递 vm.$dispatch

//子组件<template>  <input v-model="dataInput" v-on:keyup.13="addDataItem()" ></input></template><script> export default {  data () {  return {  dataInput: ""  }  },  methods : {  addDataItem () {  let self = this if( !(self.dataInput && self.dataInput.length > 0) ) { return } //派遣事件到父组件  self.$dispatch( 'addFatherDataEvent', self.dataInput ) self.dataInput = ""  }  } }</script>
//父组件<template>  <ul>  <li v-for="item in dataList">{{item}}</li>  </ul>  <component-child></component-child></template><script>import ComponentChild from './child.vue'export default {  data () {  return {  dataList : [ 'hello world!', 'welcome to use vue.js' ]  }  }, components : { ComponentChild },  events : {  addFatherDataEvent : function ( dataInput ) {  this.dataList.push( dataInput )  }  }}</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选