Home >Web Front-end >Front-end Q&A >What are the methods for passing parameters in Vue?

What are the methods for passing parameters in Vue?

青灯夜游
青灯夜游Original
2021-09-15 14:55:4211039browse

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