vue 组件通信的方式

  • 父 子组件的数据传递
  • 子父组件的数据传递
  • 兄弟组件之间的数据传递
  • 深层嵌套,祖先组件与子孙组件的数据传递

1.父子组件数据传递,子组件接收使用props

// 父组件传递参数
<cases-list :list="list" :title="案例列表"></cases-list>
// 传递静态数据时,即字符串时,可以不用v-bind绑定
<cases-list :list="list" title="案例列表"></cases-list>

// 子组件接收参数
props: {
	list: {
		type: Array,
		default: []
	},
	title: {
		type: String,
		default: ''
	}
}

2.子父组件的数据传递,子组件使用$emit传参,父组件使用函数接收

// 子组件传递参数
clickPraiseBtn(isPraise) {
	// isPraise 为点赞的状态
	this.$emit('click-praise', isPraise)
}

// 父组件接收参数
<cases-list :list="list" :title="案例列表" @click-praise="clickPraiseBtn"></cases-list>

clickPraiseBtn(isPraise) {
	// 函数里面接收子组件传递的参数,可以传多个
	this.isPraise = isPraise
}

3.兄弟组件之间的数据传递

// url传参,只适合页面跳转使用
this.$router.push({
	path: '/b',
	query: {
		id: 1,
		name: '果果'
	}
})

// eventBus传递
var eventHub = new Vue()
// 在组件中,可以使用 $emit,$on,$off 分别来分发、监听、取消监听事件
// a
addTodo: function () {
	eventHub.$emit('add-todo', { text: this.newTodoText })
    this.newTodoText = ''
}
// b
created: function () {
    eventHub.$on('add-todo', this.addTodo)
}
// 最好在组件销毁前, 清除事件监听
beforeDestroy: function () {
    eventHub.$off('add-todo', this.addTodo)
}

// 复杂的项目最好使用vuex管理(推荐)
const store = new Vuex.Store({
	state: {
	  count: 0
	},
	getters: {}, // 计算属性
	mutations: {
	  increment (state) {
	    state.count++
	  }
	}, // 同步操作
	actions: {}  // 提交mutations,异步操作
})

4.祖先组件与子孙组件的数据传递,使用provide/inject

// 父级组件提供 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// 子组件注入 'foo'
var Child = {
  inject: ['foo'],
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值