zoukankan      html  css  js  c++  java
  • 在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
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    mysql命令集锦
    linux 删除文件名带括号的文件
    linux下的cron定时任务
    struts2文件下载的实现
    贴一贴自己写的文件监控代码python
    Service Unavailable on IIS6 Win2003 x64
    'style.cssText' is null or not an object
    "the current fsmo could not be contacted" when change rid role
    远程激活程序
    新浪图片病毒
  • 原文地址:https://www.cnblogs.com/JYuAn/p/12247081.html
Copyright © 2011-2022 走看看