在nuxt中页面间传值问题


前段工程页面间跳转我们一般是这样写的:
在起始页面传递

js写法: let name = "ayasa" this.$router.push({ path : ' /404 ' , query : { name } }) html写法: <nuxt-link :to=" '/404?name=' + name ">{{ name }}</nuxt-link> 

由于使用params在页面刷新时会失效,所以这里我们尽量使用query属性,
然后在接收页面接收

 let name= this.$route.query.name

这种方法虽然有效,但会造成两个页面与前端路由耦合
解决办法是把要传递的值作为props传递给目标页面,以减少耦合
由于nuxt中将pages设置成了默认路由,这里我们手工配置路由

打开nuxt.config.js文件,在module.exports 更新以下内容
module.exports = { router: { extendRoutes(routes, resolve) { //路由配置扩展 routes.push({ name: '404', //新建路由名字 path: '/showDetail/:name', //路由路径 props: true, // 允许props component: resolve(__dirname, 'pages/404.vue') //路由组件地址 }) } } } 
保存,然后重启nuxt服务器

这样,我们在起始页面就可以这样写了

let name = "ayasa"
this.$router.push({ path : '/404/' + name }) 

或者
let name = "ayasa"
this.$router.replace({ path :  '/404?name = ' + name });

或者
<nuxt-link :to=" '/404?name=' + name ">{{ name }}</nuxt-link>

这里使用replace的原因是不会产生历史记录,无法被this.$router.go函数记录,而push函数会添加到访问记录列表,对于404页面,我们显然不希望用户在点击前进或后退按钮时看见他们出现

然后在接收端定义props选项就能使用name值了
props: { name: String }, created:{ console.log(this.name) // "ayasa" }


作者:莎与茉
链接:https://www.jianshu.com/p/bc0b4630efb6
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM