• 在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
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    centos7 rabbitmq系统部署
    socket粘包、断包、校验
    C#对象、文件与二进制串(byte数组)之间的转换
    Windows Error Code
    C#之Socket断线和重连
    BitConverter 整数和十六进制互转
    DateTime还是DateTimeOffset?Now还是UtcNow?
    WebAPI 跨域
    Console Owin 跨域解决
    2019.12.17 Arcgis10.1许可到期解决方法
  • 原文地址:https://www.cnblogs.com/JYuAn/p/12247081.html
Copyright © 2020-2023  润新知