search
HomeWeb Front-endFront-end Q&AWhat are the methods for passing parameters in Vue?

Methods for passing parameters: 1. Use "props" and "$emit" to pass parameters between parent and child components; 2. Use "provide" and "inject" to pass parameters between grandfather and grandson components; 3. Brothers Public files are used to transfer parameters between components; 4. "query" and "params" are used to transfer parameters between routes.

What are the methods for passing parameters in Vue?

The operating environment of this tutorial: windows7 system, vue version 2.9.6, DELL G3 computer.

Common parameter passing methods in Vue

  • Component communication - method calling and parameter passing between parent and child components in Vue props, $emit

  • Component communication - parameter passing between grandfather and grandson components provide, inject

  • Component communication - parameter passing between sibling components bus.js

  • Parameter query and params between routes

1. Parent-child components

1.1 Parent-to-child (props)

<!-- 父组件father.vue -->
<template>
  <div>
    <div>这里是father组件</div>
    <div>这是父组件要传给子组件的参数:{{msg}}</div>
    <!-- 1.传递:data1为动态参数msg的参数名,名字自定义,与子组件接收参数名同名
    data2为静态参数的参数名,名字自定义,与子组件接收参数名同名 -->
    <child :data1="msg" data2="777"></child>
  </div>
</template>
<script>
  import child from "./child";
  export default {
      data() {
          return {
              msg:"666"
          }
      },
    components: {
      child
    }
  };
</script>
<!-- 子组件child.vue -->
<template>
  <div>
    <div>这里是child组件</div>
    <!-- 3.使用:这里就是接收的父组件参数 -->
    <div>接受的父组件动态参数:{{ data1 }}</div>
    <div>接受的父组件静态参数:{{ data2 }}</div>
    <div>接受的父组件参数:{{ data }}</div>
  </div>
</template>
<script>
  export default {
    // 2.接收:props接收父组件参数,data1与data2为传递参数的参数名,与父组件内同名
    props: ["data1", "data2"],
    data() {
      return {
        data: "默认值"
      };
    },
    // 3.使用:直接用this调用
    mounted() {
      this.data = this.data1;
    }
  };
</script>

The page data effect is as follows

Please pay a little attention here. If the parameters passed by the parent component need to be assigned during the life cycle, they cannot be bound to mounted. Otherwise, this is called in the child component method. Will not succeed. Life cycle sequence: parent beforeMount->child beforeCreate...child mounted->parent mounted

1.2 Son to parent ($emit)

<!-- 子组件child.vue -->
<template>
  <div>
    <div>这里是child组件</div>
    <!-- 这里就是接收的父组件参数 -->
    <input type="button" value="点击向父组件传参" @click="toFather">
  </div>
</template>
<script>
  export default {
    data(){
      return{
        cmsg:&#39;我是子组件的参数&#39;
      }
    },
    methods: {
      toFather(){
        // 1.子组件触发父组件方法
        // $emit第一个参数为所要触发的父组件函数,函数名可自定义但要与父组件中对应函数名同名
        // $emit第二个参数就是子组件向父组件传递的参数
        this.$emit(&#39;receive&#39;,this.cmsg);
      }
    },
  };
</script>
<style scoped></style>
<!-- father.vue -->
<template>
  <div>
    <div>这里是father组件</div>
    <div>接收子组件参数:{{fmsg}}</div>
    <!-- 2.在对应子组件上绑定函数,这里“receive”是函数名,可自定义但要与子组件触发函数同名 -->
    <child @receive="fromChild"></child>
  </div>
</template>
<script>
  import child from "./child";
  export default {
    data() {
      return {
        fmsg:&#39;&#39;
      };
    },
    methods: {
      // 接收子组件参数,赋值
      fromChild(data){
        this.fmsg=data;
      }
    },
    components: {
      child
    }
  };
</script>
<style scoped></style>

The page rendering after clicking the button is as follows

##1.3 The parent component calls the child component method ($on)

<!-- father.vue -->
<template>
    <div>
        <div @click="click">点击父组件</div>
        <child ref="child"></child>
    </div>
</template>

<script>
    import child from "./child";
    export default {
        methods: {
            click() {
                this.$refs.child.$emit(&#39;childMethod&#39;,&#39;发送给方法一的数据&#39;) // 方法1:触发监听事件
                this.$refs.child.callMethod() // 方法2:直接调用
            },
        },
        components: {
            child,
        }
    }
</script>
<!-- child.vue -->
<template>
    <div>子组件</div>
</template>

<script>
    export default {
        mounted() {
            this.monitoring() // 注册监听事件
        },
        methods: {
            monitoring() { // 监听事件
                this.$on(&#39;childMethod&#39;, (res) => {
                    console.log(&#39;方法1:触发监听事件监听成功&#39;)
                    console.log(res)
                })
            },
            callMethod() {
                console.log(&#39;方法2:直接调用调用成功&#39;)
            },
        }
    }
</script>

2. Parameter passing of grandson component (provide and inject, not affected by component level)

provide and inject mainly provide use cases for high-level plug-in/component libraries. Not recommended for use directly in application code. Official documentation:
https://cn.vuejs.org/v2/api/#provide-inject
https://cn.vuejs.org/v2/guide/components-edge -cases.html#Dependency injection

<!-- grandpa.vue -->
        data() {
            return {
                msg: &#39;A&#39;
            }
        },
        provide() {
            return {
                message: this.msg
            }
        }
<!-- father.vue -->
        components:{child},
        inject:[&#39;message&#39;],
<!-- child.vue -->
        inject: [&#39;message&#39;],
        created() {
            console.log(this.message)    // A
        },

3. Parameter passing of sibling components (bus.js)

3.1 Create bus.js

##3.2 Pass parameters like sibling components

import Bus from "@/utils/bus";   //注意引入
    export default {
        data(){
            return {
                num:1
            }
        },
        methods: {
            handle(){
                Bus.$emit("brother", this.num++, "子组件向兄弟组件传值");
            }
        },
    }

3.3 Accept parameters from sibling components

import Bus from "@/utils/bus";   //注意引入
    export default {
        data(){
            return {
                data1:&#39;&#39;,
                data2:&#39;&#39;
            }
        },
        mounted() {
            Bus.$on("brother", (val, val1) => {    //取 Bus.$on
                this.data1 = val;
                this.data2 = val1;
            });
        },
    }

4. Parameter transfer between routes (query and params)

query and parmas are used in roughly the same way, here Briefly introduce the routing configuration, parameter transfer and calling

4.1params, the parameters are displayed in the url

// router的配置
    {
      path: "/two/:id/:data",     // 跳转的路由后加上/:id,多个参数继续按格式添加,数据按顺序对应
      name: "two",
      component: two
    }

// 跳转,这里message为123
  this.$router.push({
    path: `/two/${this.message}/456`     // 直接把数据拼接在path后面
  });
 // 接收
  created() {
      this.msg1=this.$route.params.id    // 123
      this.msg2=this.$route.params.data  // 456
   }

// url显示,数据显示在url,所以这种方式传递数据仅限于一些不那么重要的参数
  /two/123/456

4.2params, the parameters are not displayed in the url, and the data disappears when the page is refreshed

// router的配置
    {
      path: "/two",
      name: "two",
      component: two
    }
// 跳转,这里message为123
    this.$router.push({
      name: `two`,    // 这里只能是name,对应路由
      params: { id: this.message, data: 456 }
    });
 // 接收
  created() {
      this.msg1=this.$route.params.id    // 123
      this.msg2=this.$route.params.data  // 456
   }

// url显示,数据不显示在url
  /two

4.3query, the parameters are displayed in the url

// router的配置
    {
      path: "/two",
      name: "two",
      component: two
    }
// 跳转,这里message为123
    this.$router.push({
      path: `/two`,    // 这里可以是path也可以是name(如果是name,name:&#39;two&#39;),对应路由
      query: { id: this.message, data: 456 }
    });
 // 接收
  created() {
      this.msg1=this.$route.query.id    // 123
      this.msg2=this.$route.query.data  // 456
   }

// url显示,数据显示在url
  /two?id=123&data=456
Related recommendations: "

vue.js Tutorial

"

The above is the detailed content of What are the methods for passing parameters in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft