vue的父子组件通信传值

vue的父子组件传值

1. 使用props进行父传子

  • 父组件在使用子组件时进行绑定传值
  • 子组件使用props数组接收父组件传来的值
let comp = {
	data(){
		return {
			
		}
	},
	/*props接收父组件的传值*/
	props: [name, g],
	template: `
		<p>name, g</p>
	`
}
new Vue({
	el: "#id",
	data {
		name: "vue",
		google: "google"
	},
	components: {
		comp
	},
	template: `
		<!--绑定传值-->
		<comp :name = "name" :g = "google"></comp>
	`
})

2. 使用事件触发进行子传父

父组件定义事件方法
子组件中的点击事件中通过$emit触发父组件的方法,从而进行传值

let comp = {
	data(){
		return {
			id: 1;
		}
	},
	template: `
		<button @click="clickHandler"></button>
	`,
	methods: {
		clickHandler(){
			this.$emit("clickMethod", this.id)
		}
	}
}
new Vue({
	el: "#id",
	data: {
		name: "vue"
	},
	components: {
		comp
	},
	template: `
		<comp @clickMethod = "inputValue"></comp>
	`,
	methods: {
		inputValue(data){
			console.log('父组件获取值', data);
		}
	}
})

3. 使用ref进行父传子

子组件使用ref注册引用

这些注册引用信息会保存在父组件的 r e f s 中 , 父 组 件 通 过 refs中,父组件通过 refsrefs可以获取子组件,通过调用子组件的方法进行传值

let comp = {
	data(){
		return {
			id: 1
		}
	}
}
new Vue({
	el: "#id",
	data: {
		
	},
	components: {
		comp
	},
	template: `
		<comp ref="sonComponent"></comp>
	`,
	methods: {
		handler(){
			/*
			this.$refs.sonComponent获取子组件
			*/
		}
	}
})

4. 使用事件总线进行组件间通信

事件总线需要新建一个新的vue实例,称作bus

let bus = new Vue({});

如果组件A需要向组件B进行传值

  • 在A中需要进行触发事件
  • 在B中需要进行监听事件
// 组件A中
bus.$emit('事件名', data);

// 组件B中
bus.$on('事件名', function(data){/*...*/})

5. vuex

当项目越来越复杂的时候,事件总线使用则会越来越混乱,命名也会冲突,所以引入vuex

vuex是一个专门为vue.js应用程序开发的状态管理工具,它采用集中式存储管理应用的所有组件的共享状态

vuex中的state用于保存所有组件的共享状态,mutation是唯一修改state的入口,action是用于进行共享状态的异步请求的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值