Vue 组件传值的方式

1. bus总线方式

bus 总线是为了实现兄弟组件之间传值的一种方式

  1. 新建一个Bus 实例
  2. 使用 b u s bus 上的 emit 触发on-input事件
  3. 使用$on 监听 $bus 上的 on-input 事件
// bus.js
import Vue from 'vue'
const Bus = new Vue()
export default Bus

main.js 在Vue原型上添加$bus

import Vue from 'vue'
import bus from './bus'
Vue.prototype.$bus = bus

a 组件(Ainput.vue)使用emit 触发on-input事件并且传值

<template>
	<input  @input='handleInput'/>
</template>
<script>
export default{
	data () {
		return {
		}
	},
	methods: {
		handleInput (event) {
			this.$bus.$emit('on-input', event.target.value)
		}
	}
}
<script>

b Bshow组件 使用 $on 来监听 on-input 事件 获取 a组件传入的值

<template>
	<div> {{ inputVal }} </div>
</template>
<script>
export default{
	data () {
		return{
			inputVal: ''
		}
	},
	mounted() {
		this.$bus.$on('on-input', val => {
			this.inputVal = val
		})
	}
}
</script>

home.vue 引入两个组件进行测试

<template>
	<div>
		<Ainput />
		<Bshow />
	</div>
</template>
<script>
	import Ainput from '@/components/Ainput'
	import Bshow from '@/components/Bshow'
	export default {
		components: {
			Ainput,
			Bshow
		}
	}
</script>

2.父组件向子组件传参

1.父组件通过 v-on 动态绑定一个值传到子组件
2.子组件通过props 接收父组件传来的值

// 父组件
<template>
	<div>
		<Bshow :title='msg'/>
	</div>
</template>
<script>
import Bshow from '@/components/Bshow'
export default{
	data() {
		return {
			msg: 'hello word'
		}
	},
	components: {
		Bshow
	}
}
</script>

子组件 Bshow.vue

<template>
 <div> {{ title }} <div>
</template>
// 数组写法
export default{
	props: ['title']
}
// 对象写法
export default{
	props: {
		title: {
			type: String, // 接收的类型
			required: true, // 是否必填
			default: 'title'  // 默认值
		}
	}
}

3. $emit 传值(子组件向父组件传值)

子组件触发一个自定义事件 $emit()
父组件监听该自定义事件 $on()
以达到子组件的值改变父组件的值也实时更新

// 子组件  
<template>
	<div>
		<input  @click='handleClick'/>
	</div>
</template>
<script>
export default{
	methods: {
		handleClick() {
			// 第一种写法
			this.$emit('on-click', 'hello word')
			// 第二种写法
			this.$emit('update:title', 'hello word')
		}
	}
}
</script>

父组件

<template>
<div>
	<!-- 第一种写法  监听自定义事件-->
	<emit @on-click='say'><.emit>
	<!-- 第二种写法- sync 修饰符 ->
	<emit :title.sync='msg'></emit>
	{{ msg }}
</div>
</template>
<script>
import emit from '_c/emit'
export default{
	components: {
		emit
	},
	methods: {
		say (data) {
			// hello word
			console.log(data)
		}
	}
}
</script>
发布了16 篇原创文章 · 获赞 10 · 访问量 1032

猜你喜欢

转载自blog.csdn.net/qq_39557024/article/details/104400380
今日推荐