vue点击跳转到另一个页面(vue页面跳转和参数传递)
导读:目标:两种方式,实现vue组件间跳转和参数传递...
目标:两种方式 ,实现vue组件间跳转和参数传递
一 、路由方式
页面跳转
当前组件使用$.router.push ,通过参数name对应路由中目标组件的name实现跳转参数传递
传值:当前组件使用$.router.push ,通过参数query对应路由里目标组件props中的route.query 接参:目标组件script中使用$.router.query接收参数 ,页面中直接写参数名(方法不唯一 ,还有其他方式)
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>二 、组件方式
只需配置一个路由即可实现不同页面跳转 ,页面跳转和参数传递通过组件间调用实现
页面跳转
父组件 → 子组件 引用子组件 ,利用v-if标签分别选择显示对应组件 子组件 → 父组件 子组件使用$.emit(事件)调用父组件方法改变自定义参数(show)实现跳转参数传递
父组件 → 子组件 传值:父组件引用子组件标签(<my-detail :id="父组件参数"></my-detail>)中传递参数 接参:子组件接收参数使用props:[id] 子组件 → 父组件 传值:子组件使用$.emit(父组件方法,参数)传递参数 接参:父组件通过方法名(参数)接收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>【源码见个人空间资源板块】
原创不易 ,转载请注明来源
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!