Vue3 setup context参数

作者: 温新

分类: 【Vue.js】

阅读: 6815

时间: 2021-08-22 11:12:27

作者:温新

时间:2021-08-22

hi,我是温新,一名PHPer

setup函数中的context参数

context参数是一个普通的javascript对象,它对组件暴露三个属性:attrsslotsemit

context--attrs

attrs用途:当父组件传递数据给子组件时,子组件不通过props接收,那么父组件传递的数据就到了setup中的contextattrs属性。

<div id="app">
	<!-- 父组件传递数据给子组件 -->
	<son webName="自如初"></son>
</div>

<script>
	const app = Vue.createApp({
	});

	// 子组件不使用props接收
	app.component('son', {
		template:`<div>son</div>`,

		setup(props, context) {
			const { attrs, slots, emit} = context;
			// 打印父组件传递的数据
			console.log(attrs.webname);
			return {};
		}
	});
	const vm = app.mount('#app');
</script>

context--slots

slots:用于接收渲染父组件传递的插槽内容。

<div id="app">
	<son>
		父组件通插槽传递的内容
	</son>
</div>

<script>
	const app = Vue.createApp({
	});

	app.component('son', {
		template:`<div>son</div>`,

		setup(props, context) {
			const { h } = Vue;
			const { attrs, slots, emit} = context;
			
			// 显示父组件传递的内容
			return () => h('p', {}, slots.default());
		}
	});
	const vm = app.mount('#app');
</script>

context--emit

用途:向父组件触发事件。

<div id="app">
	<!-- 4、父组件监听子组件发射的事件 -->
	<son @sclick="getData"></son>
</div>

<script>
	const app = Vue.createApp({
		methods: {
			// 5、实现事件
			getData () {
				alert(1)
			}
		}
	});

	app.component('son', {
		// 1、子组件中绑定事件
		template:`<div @click="sonClick">son</div>`,

		setup(props, context) {
			const { attrs, slots, emit} = context;
			
			function sonClick() {
				// 2、通过 emit 向父组件发射事件
				emit('sclick');
			}

			 // 3、对外暴露该事件
			return { sonClick };
		}
	});
	const vm = app.mount('#app');
</script>
请登录后再评论