目标:两种方式,实现vue组件间跳转和参数传递

一、路由方式

页面跳转

参数传递

(方法不唯一,还有其他方式)

1. 路由

const router = new Router({
	routes: [{
		path: '/list',
		name: 'List',
		component: () => import('@/components/demo2/List.vue')
	},{
		path: '/detail',
		name: 'Detail',
		component: () => import('@/components/demo2/Detail.vue'),
		props: route => ({param: route.query.param})
	}]
})

2. 列表页面

<template>
	<div>
		<h1>列表页面</h1>
		<div>
			<el-button type="primary" @click="toDetail">点击跳转详情</el-button>
		</div>
	</div>
</template>
<script>
	export default {
		name: "List",
		data() {
			return {
				myId: "123"
			};
		},
		methods: {
			toDetail() {
				this.$router.push({
					name: 'Detail',
					query: {param: this.myId}
				})
			}
		}
	}
</script>

3. 详情页面

<template>
	<div>
		<h1>详情页面</h1>
		<div>
			<el-button type="primary" @click="toList">点击返回列表</el-button>
			<div>传递参数:{{myId}}</div>
		</div>
	</div>
</template>
<script>
	export default {
		name: "Detail",
		data() {
			return {
				myId : this.$route.query.param
			};
		},
		methods:{
			toList(){
				this.$router.push({
					name: 'List',
				})
			}
		}
	}
</script>

二、组件方式

只需配置一个路由即可实现不同页面跳转,页面跳转和参数传递通过组件间调用实现

页面跳转

参数传递

1. 路由

const router = new Router({
	routes: [{
		path: '/main',
		name: 'Main',
		component: () => import('@/components/demo1/Main.vue')
	}]
})

2. 主页组件

<template>
	<div>
		<h1>主页面</h1>
		<my-list v-if="show == 'list'" @toDetail="toDetail"></my-list>
		<my-detail v-if="show == 'detail'" @toList="toList" :myId="myId"></my-detail>
	</div>
</template>
<script>
	import MyList from "@/components/demo1/MyList"
	import MyDetail from "@/components/demo1/MyDetail"
	export default {
		name: "Main",
		components: {
			MyList,
			MyDetail
		},
		data() {
			return {
				show: "list",
				myId: ""
			};
		},
		methods:{
			toDetail(data){
				this.show = "detail"
				this.myId = data
			},
			toList(){
				this.show = "list"
			}
		}
	}
</script>

3. 列表子组件

<template>
	<div>
		<h2>列表页面</h2>
		<div>
			<el-button type="primary" @click="toDetail">点击跳转详情</el-button>
		</div>
	</div>
</template>
<script>
	export default {
		name: "MyList",
		data() {
			return {
				myId: "123"
			};
		},
		methods: {
			toDetail(data) {
				this.$emit("toDetail",this.myId)
			}
		}
	}
</script>

4. 详情子组件

<template>
	<div>
		<h2>详情页面</h2>
		<div>
			<el-button type="primary" @click="toList">点击返回列表</el-button>
			<div>传递参数:{{myId}}</div>
		</div>
	</div>
</template>
<script>
	export default {
		name: "MyDetail",
		props:['myId'],
		data() {
			return {
			};
		},
		methods:{
			toList(){
				this.$emit("toList")
			}
		}
	}
</script>

【源码见个人空间资源板块】

原创不易,转载请注明来源

发表回复