Vue.js 中的参数传递 - 煎饼果子

Vue.js 中的参数传递

首页 / 技术之路 / 正文

最近在复习(学习)Vue.js 相关的知识,其中路由Router和参数传递是一个十分重要且较难的知识。于是花时间整理了一下下,希望对自己有用~

1. 通过 name 传递参数

export default new Router({
   routes: [
       {
           path: '/',
           name: 'index',
           component: index
       },{
           path: '/page',
           name: 'page',
           component: page
       }
   ] 
});

我们常把页面的路由配置在 /src/router 文件夹下的 index.js 文件中,如上为配置的内容。这其中的 name 属性是可以作为参数传递的,在模版中直接只用 {{$route.name}} 接收,即可以在模版中显示。


2. 通过 < router-link > 中的 to 传递参数

使用 < router-link to=" /page "> page < /router-link > 可以实现页面的跳转,这里面 to 是可以带上参数跳转的,我们需要在给 to 进行绑定,即 :to(v-bind:to)

<router-link :to="{name:'page',params:{data:'我是App.vue传至page.vue的参数'}}" >page</router-link>
  • 这其中需要注意的是要给 to 加上绑定,后面跟的是对象形式的字符串。
  • 其中的 name 是我们在路由配置文件(上图图二)中配置的 name 两者要对应。
  • params 即是我们要传的参数,它可以是多个值。

随后在对应的模版页面中(这里为 page.vue)进行接收。

{{$route.params.data}}  

3. 在业务逻辑中实现页面跳转并传参

当在业务逻辑中需要实现页面跳转经常能够使用到编程式导航:

  • this.$router.go(1),进入下一级
  • this.$router.back(-1),返回上一级,通俗的说就是前进与后退。
  • this.$router.push(’/page’),跳转到 page.vue

那么我们应该如何传递参数呢?例如,我们在判断完某个条件后需要跳转到 page 页并且需要传递 ageaddress 两个参数过去,我们的操作方法是:

App.vue

<div @click="toPage">page</div>

我们在需要的地方加上点击事件:

toPage(){
      this.$router.push({
        name: 'page',
        params: {
          age: 22,
          address: 'China'
        }
      })
    }

随后在 methods 中写入该事件,需要注意的是这里面的 name 同样是要与在配置路由时配置的 name 属性保持一致。
params 是我们传入的参数,可以是常量也可以是变量。

page.vue
在 page.vue 中接收参数,可以在生命周期的 mounted() 接收并且放入 data ,再在模版上显示出来。

<template>
    <div>
        {{myage}}-{{myaddress}}
    </div>
</template>

<script>
    export default {
        name: "page111",
        data() {
            return {
                myage: '',
                myaddress: ''
            }
        },
        mounted(){
            // 在挂载时接收到参数并且赋值
            this.myage = this.$route.params.age;
            this.myaddress = this.$route.params.address;
        },
    }
</script>

4. 利用 url 传参

在项目开发过程中常常通过 url 进行参数传递,在 vue-cli 中该如何操作呢?

  1. 在配置路由处以冒号形式,在 url 后方加上参数(/src/router/index.js)

    {
     path: '/page/:pageId/:pageTitle',
     name: 'page',
     component: page
    }
  2. <router-link></router-link>to 属性中加入参数(App.vue)

    <template>
      <div id="app">
     <img src="./assets/logo.png"><br/>
       <router-link to="/" >index</router-link>
       <router-link to="/page/1/标题" >page</router-link>
     <router-view/>
      </div>
    </template>
  3. 在 page.vue 中接收参数

    <template>
     <div>
         <p>id: {{$route.params.pageId}}</p>
         <p>标题: {{$route.params.pageTitle}}</p>
     </div>
    </template>

5. 父组件与子组件之间传参

项目中组件是经常被使用到的,那么父组件与子组件之间的联动是非常重要的。

父传子

  1. 先建立一个组件并且使用,在 components 文件夹下新建 component.vue 文件作为组件。

    <template>
     <div>
         <p>我的组件 {{msg}}-{{content}}</p>
     </div>
    </template>
    
    <script>
     export default{
         name: 'child',
         props: ["msg","content"],
     }
    </script>

    随后在 page.vue 中引入该组件,在 <script> </script>import 且引用,随后在模版中使用,如下:

    <template>
     <div>
         <children></children>
     </div>
    </template>
    
    <script>
     import children from "./component";
     export default {
         name: "page",
         components: {
             children
         }
     }
    </script>

    要传递参数,可以在 <children> </children>标签中加入要传入的参数,并且在组件(component.vue)中使用 props 接收再使用插值在模版中显示。
    同时我们也可以给要传的参数绑定起来,如下第二种写法,在参数前加上冒号(v-bind)这样我们就能在 data 中编辑我们的参数了。

    // page.vue
    <children msg="我是信息" content="我是内容"></children>
    
    <children :msg="message" :content="content"></children>
    <script>
     import children from "./component";
     export default{
         name: 'page',
         components: {
             children
         },
         data(){
             return {
                 message: '我是信息',
                 content: '我是内容'
             }
         }
     }
    </script>
    
    // component.vue
    <p>我的组件 {{msg}}-{{content}}</p>
    
    <script>
     export default{
         name: 'child',
         props: ["msg","content"]
     }
    </script>

子传父

子组件再传值回父组件,在函数中使用 this.$emit()

// component.vue
<script>
    export default{
        name: 'component',
        data() {
            return {
                param:"需要传回的参数",
                data: "参数2"
            }
        },
        props: ["msg","content"],
        methods: {
            // 假设在子组件选择完毕后点击将 param 传回
            chooseOk(){
                // ...中间的逻辑处理省略
                this.$emit('changeData',this.param,this.data);
            }
        }
    }
</script>

在 page.vue 的 <children> 标签中加入 @changeData,即可在点击子组件之后在父组件出接收到传过来的参数

<children :msg="msg" :content="content" @changeData="dataChange"></children>

<script>
    import children from "./component";
    export default {
        name: "page",
        components: {
            children
        },
        methods: {
            dataChange(param,data){
                console.log(param + ',' + data);
            }
        }
    }
</script>

最后在附加一点,在父组件中该如何调用子组件中的函数呢,这里需要用到 ref 属性,添加在我们的 <children> 标签中

// page.vue
<div @click="ifClick">click</div>
<children ref="child" :msg="msg" :content="content" @changeData="dataChange"></children>
// page.vue
// 重复部分省略 ...
methods: {
    ifClick(){
        this.$refs.child.isClick();
    }
}

// component.vue
methods: {
    isClick(){
        console.log("父组件点击了");
    }
}
评论区
头像
    头像
    流量卡知识网
    2023年10月05日 10:35
    回复

    你好,看完你的博客文章,感觉很不错!希望与你网站首页友情链接
    流量卡知识网
    http://53go.cn/
    专注于移动/联通/电信推出的大流量多语音活动长短期套餐手机卡的相关知识的介绍普及

    听说互换友情链接可以增加网站的收录量,特此来换,如果同意的话就给internetyewu@163.com[微信ganenboy]发信息或者就在此回复下吧!

文章目录