Home  >  Article  >  What are the ways to pass values ​​in vue components?

What are the ways to pass values ​​in vue components?

百草
百草Original
2023-06-19 15:23:0412047browse

The way vue components pass values: 1. Pass from parent to child, define "props" in the child component to receive it; 2. Pass from child to parent, use "$emit()" to trigger in the child component; 3. Brothers Pass value, define the event bus "eventBus"; 4. Pass value with question mark, colon and parent-child components; 5. Use "$ref" to pass value; 6. Use "inject" to inject the data of the parent component into the current instance; 7. From ancestor to grandchild; 8. From grandson to ancestor; 9. $parent; 10. SessionStorage value transfer; 11. vuex.

What are the ways to pass values ​​in vue components?

The operating system of this tutorial: Windows 10 system, vue version 3.0, Dell G3 computer.

What are the ways to pass values ​​in vue components?

1. Pass the parent component to the child component

Define a props in the child component, that is, props:['msg' ], msg can be an object or a basic data type

If you want to define a default value, that is, props:{msg: {type: String, default: 'hello world'}},

If the default value is an object type: props: { msg: { type: Object, default: () => { return { name: 'dan_seek' } } }}

You need to pay attention to this Value transfer is one-way, you cannot change the value of the parent component (except for reference types, of course); and if you directly modify the value of props, a warning will be reported.

The recommended way to write is to redefine a variable in data() (see Children.vue) and assign props to it. Of course, calculated properties will also work.

Children.vue

<template>
    <section>
        父组件传过来的消息是:{{myMsg}}
    </section>
</template>
<script>
    export default {
        name: "Children",
        components: {},
        props:[&#39;msg&#39;],
        data() {
            return {
                myMsg:this.msg
            }
        },
        methods: {}
    }
</script>

Parent.vue

<template>
  <div class="parent">
    <Children :msg="message"></Children>
  </div>
</template>
<script>
import Children from &#39;../components/Children&#39;
export default {
  name: &#39;Parent&#39;,
  components: {
      Children
  },
  data() {
      return {
          message:&#39;hello world&#39;
}
},
}
</script>

2. Pass the child component to the parent component

You need to use self here Define the event, use this.$emit('myEvent') to trigger it in the child component, and then use @myEvent to listen in the parent component

Children.vue

<template>
    <section>
        <br>
        <div @click="clickme">click me</div>
    </section>
</template>
<script>
    export default {
        name: "Children",
        components: {},
        data() {
            return {
                childNum:0
            }
        },
        methods: {
            clickme(){
                // 通过自定义事件addNum把值传给父组件
                this.$emit(&#39;addNum&#39;,this.childNum++)
            }
        }
    }
</script>

Parent.vue

<template>
    <div class="parent">
        这里是计数:{{parentNum}}
        <Children-Com @addNum="getNum"></Children-Com>
    </div>
</template>
<script>
    import ChildrenCom from &#39;../components/Children&#39;
    export default {
        name: &#39;Parent&#39;,
        components: {
            ChildrenCom
        },
        data() {
            return {
                parentNum: 0
            }
        },
        methods:{
            // childNum是由子组件传入的
            getNum(childNum){
                this.parentNum = childNum
            }
        }
    }
</script>

3. Transferring values ​​between sibling components

Use the triggering and monitoring capabilities of custom event emit to define a public event bus eventBus. Through it as an intermediate bridge, we Values ​​can be passed to any component. And through the use of eventBus, you can deepen your understanding of emit.

EventBus.js

import Vue from &#39;vue&#39;
export default new Vue()

Children1.vue

<template>
    <section>
        <div @click="pushMsg">push message</div>
        <br>
    </section>
</template>
<script>
    import eventBus from &#39;./EventBus&#39;
    export default {
        name: "Children1",
        components: {},
        data() {
            return {
                childNum:0
            }
        },
        methods: {
            pushMsg(){
            // 通过事件总线发送消息
                eventBus.$emit(&#39;pushMsg&#39;,this.childNum++)
            }
        }
    }
</script>

Children2.vue

<template>
    <section>
        children1传过来的消息:{{msg}}
    </section>
</template>
<script>
    import eventBus from &#39;./EventBus&#39;
    export default {
        name: "Children2",
        components: {},
        data() {
            return {
                msg: &#39;&#39;
            }
        },
        mounted() {
        // 通过事件总线监听消息
            eventBus.$on(&#39;pushMsg&#39;, (children1Msg) => {
                this.msg = children1Msg
            })
        }
    }
</script>

Parent.vue

<template>
    <div class="parent">
        <Children1></Children1>
        <Children2></Children2>
    </div>
</template>
<script>
    import Children1 from &#39;../components/Children1&#39;
    import Children2 from &#39;../components/Children2&#39;
    export default {
        name: &#39;Parent&#39;,
        components: {
            Children1,
            Children2
        },
        data() {
            return {
            }
        },
        methods:{
        }
    }
</script>

Also available on github An open source vue-bus library, you can refer to: https://github.com/yangmingshan/vue-bus#readme

4. Passing values ​​between routes

i. Use question marks to pass values

When page A jumps to page B, use this.$router.push('/B?name=danseek')

Page B can use this.$route .query.name to get the value passed from page A

Please note the difference between router and route

ii. Use colon to pass the value

Configure the following route:

{
    path: &#39;/b/:name&#39;,
    name: &#39;b&#39;,
    component: () => import( &#39;../views/B.vue&#39;)
  },

On page B, you can use this.$route.params.name to get the value of the name passed in by the route

iii. Use the parent-child component to pass the value

Due to router-view It is also a component itself, so we can also use the parent-child component value transfer method to pass values, and then add props to the corresponding sub-page. Because the route is not refreshed after the type is updated, we cannot directly obtain the latest type directly in the mounted hook of the sub-page. value, use watch instead.

<router-view :type="type"></router-view>
// 子页面
......
props: [&#39;type&#39;]
......
watch: {
            type(){
                // console.log("在这个方法可以时刻获取最新的数据:type=",this.type)
            },
        },

5. Use $ref to pass value

Use the ability of $ref to define an ID for the child component, and the parent component can be directly accessed through this ID Methods and properties in child components

First define a child component Children.vue

<template>
    <section>
        传过来的消息:{{msg}}
    </section>
</template>
<script>
    export default {
        name: "Children",
        components: {},
        data() {
            return {
                msg: &#39;&#39;,
                desc:&#39;The use of ref&#39;
            }
        },
        methods:{
            // 父组件可以调用这个方法传入msg
            updateMsg(msg){
                this.msg = msg
            }
        },
    }
</script>

Then reference Children.vue in the parent component Parent.vue and define the ref attribute

<template>
    <div class="parent">
        <!-- 给子组件设置一个ID ref="children" -->
        <Children ref="children"></Children>
        <div @click="pushMsg">push message</div>
    </div>
</template>
<script>
    import Children from &#39;../components/Children&#39;
    export default {
        name: &#39;parent&#39;,
        components: {
            Children,
        },
        methods:{
            pushMsg(){
                // 通过这个ID可以访问子组件的方法
                this.$refs.children.updateMsg(&#39;Have you received the clothes?&#39;)
                // 也可以访问子组件的属性
                console.log(&#39;children props:&#39;,this.$refs.children.desc)
            }
        },
    }
</script>

6. Use dependency injection to pass it on to descendants and great-grandchildren

Assume that the parent component has a method getName() and needs to provide it to all descendants

provide: function () {
  return {
    getName: this.getName()
  }
}

provide Options allow us to specify the data/methods we want to provide to descendant components

Then in any descendant component, we can use inject to inject the data/methods of the parent component into the current instance:

inject: [&#39;getName&#39;]

Parent.vue

<template>
    <div class="parent">
        <Children></Children>
    </div>
</template>
<script>
    import Children from &#39;../components/Children&#39;
    export default {
        name: &#39;Parent&#39;,
        components: {
            Children,
        },
        data() {
            return {
                name:&#39;dan_seek&#39;
            }
        },
        provide: function () {
            return {
                getName: this.name
            }
        },
    }
</script>

Children.vue


<script>
    export default {
        name: "Children",
        components: {},
        data() {
            return {
            }
        },
        inject: [&amp;#39;getName&amp;#39;],
    }
</script>

7, ancestral grandson $attrs

Normally, you need to use the father’s props as an intermediary Transition, but in this way, the parent component will have some more attributes that have nothing to do with the business of the parent component, and the coupling degree is high. It can be simplified with the help of $attrs, and neither the ancestor nor the grandson need to make modifications

GrandParent.vue

<template>
    <section>
        <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent>
    </section>
</template>
<script>
    import Parent from &#39;./Parent&#39;
    export default {
        name: "GrandParent",
        components: {
          Parent
        },
        data() {
            return {}
        },
        methods: {
          sayKnow(val){
            console.log(val)
          }
        },
        mounted() {
        }
    }
</script>

Parent.vue

<template>
  <section>
    <p>父组件收到</p>
    <p>祖父的名字:{{name}}</p>
    <children v-bind="$attrs" v-on="$listeners"></children>
  </section>
</template>
<script>
  import Children from &#39;./Children&#39;
  export default {
    name: "Parent",
    components: {
      Children
    },
    // 父组件接收了name,所以name值是不会传到子组件的
    props:[&#39;name&#39;],
    data() {
      return {}
    },
    methods: {},
    mounted() {
    }
  }
</script>

Children.vue

<template>
  <section>
    <p>子组件收到</p>
    <p>祖父的名字:{{name}}</p>
    <p>祖父的性别:{{sex}}</p>
    <p>祖父的年龄:{{age}}</p>
    <p>祖父的爱好:{{hobby}}</p>
    <button @click="sayKnow">我知道啦</button>
  </section>
</template>
<script>
  export default {
    name: "Children",
    components: {},
    // 由于父组件已经接收了name属性,所以name不会传到子组件了
    props:[&#39;sex&#39;,&#39;age&#39;,&#39;hobby&#39;,&#39;name&#39;],
    data() {
      return {}
    },
    methods: {
      sayKnow(){
        this.$emit(&#39;sayKnow&#39;,&#39;我知道啦&#39;)
      }
    },
    mounted() {
    }
  }
</script>

Display results

Parent component receives

Grandfather’s name: grandParent

Subcomponent received

Grandfather’s name:

Grandfather’s gender: Male

Grandfather’s age: 88

Grandfather’s hobbies: code

8, Sun Chuanzu

With the help of $listeners intermediate events, Sun can conveniently notify Zu. For code examples, see 7

9, $parent

You can get the parent component instance through parent, and then you can access the properties and methods of the parent component through this instance. It also has a brother root, which can get the root component instance.

Syntax:

// 获父组件的数据
this.$parent.foo
// 写入父组件的数据
this.$parent.foo = 2
// 访问父组件的计算属性
this.$parent.bar
// 调用父组件的方法
this.$parent.baz()

So, in the example of passing a child component to a parent component, you can use this.$parent.getNum(100) to pass the value to the parent component.

10. Pass value to sessionStorage

sessionStorage 是浏览器的全局对象,存在它里面的数据会在页面关闭时清除 。运用这个特性,我们可以在所有页面共享一份数据。

语法:

// 保存数据到 sessionStorage
sessionStorage.setItem(&#39;key&#39;, &#39;value&#39;);
// 从 sessionStorage 获取数据
let data = sessionStorage.getItem(&#39;key&#39;);
// 从 sessionStorage 删除保存的数据
sessionStorage.removeItem(&#39;key&#39;);
// 从 sessionStorage 删除所有保存的数据
sessionStorage.clear();

注意:里面存的是键值对,只能是字符串类型,如果要存对象的话,需要使用 let objStr = JSON.stringify(obj) 转成字符串然后再存储(使用的时候 let obj = JSON.parse(objStr) 解析为对象)。

这样存对象是不是很麻烦呢,推荐一个库 good-storage ,它封装了sessionStorage ,可以直接用它的API存对象

// localStorage
 storage.set(key,val) 
 storage.get(key, def)
 
 // sessionStorage
 storage.session.set(key, val)
 storage.session.get(key, val)

更多请移步:https://github.com/ustbhuangyi/storage#readme

11、vuex

这里我也不打算介绍这个大名鼎鼎的vuex怎么用,因为要把它写清楚篇幅太长了…

如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您也许不需要使用 Vuex。

The above is the detailed content of What are the ways to pass values ​​in vue components?. 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