Home Common Problem How to pass value to vue component

How to pass value to vue component

Jul 18, 2023 am 09:27 AM
vue vue component passing value

The way to pass value in vue component: 1. Pass from father to son; 2. Pass from son to father; 3. Pass value from brother; 4. Pass value with question mark, colon and parent-child component; 5. Use " $ref" passes the value; 6. Use "inject" to inject the data of the parent component into the current instance; 7. Pass from ancestor to grandson; 8. Pass from grandson to ancestor; 9. $parent; 10. Pass value to sessionStorage; 11. vuex.

How to pass value to vue component

1. Pass the parent component to the child component

Define a props in the child component, that is, props:['msg'], msg It 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 the object type: props: { msg: { type: Object, default: () => { return { name: 'dan_seek' } } }}

It should be noted that this type of value passing is One-way, you cannot change the value of the parent component (except for reference types, of course); and if you modify the value of props directly, 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>
Copy after login

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>
Copy after login

2. Pass the child component to the parent component

You need to use custom events here, in the child component Use this.$emit('myEvent') to trigger, 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>
Copy after login

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>
Copy after login

3, Passing 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 can pass values ​​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>
Copy after login

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>
Copy after login

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>
Copy after login

There is also an open source vue-bus library on github, you can refer to it below : https://github.com/yangmingshan/vue-bus#readme

4. Passing values ​​between routes

i. Use question marks to pass values

A page jump When using 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 above

ii. Use colon to pass value

Configure the following route:

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

On page B, you can pass 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

Since the router-view itself is also a component, we can also use the parent-child component to pass the value. value, and then add props to the corresponding subpage. Because the route is not refreshed after the type is updated, you cannot directly obtain the latest type value directly in the mounted hook of the subpage, but use watch.

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

5. Use $ref to pass value

Use the ability of $ref to define an ID for the subcomponent. The parent component can directly access the methods and methods in the subcomponent through this ID. Attribute

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>
Copy after login

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>
Copy after login

6. Use dependencies Injection to descendants and great-grandchildren

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

provide: function () {
  return {
    getName: this.getName()
  }
}
Copy after login

The provide option allows us to specify what we want to provide to descendant components Data/Methods

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;]
Copy after login

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>
Copy after login

Children.vue


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

7, Ancestral grandson$attrs

Normally, you need to use the father's props as an intermediate transition, but in this way, the father component will have more things that have nothing to do with the business of the parent component. Attributes, high coupling, can be simplified with the help of $attrs, and neither ancestor nor grandchild needs to be modified

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>
Copy after login

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>
Copy after login

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>
Copy after login

Display results

Parent component receives

Grandfather’s name: grandParent

Child component receives

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 the ancestor. For code examples, see 7

9, $parent

You can get the parent component instance through parent, and then you can access the properties of the parent component through this instance. and method, it also has a sibling root, which can obtain the root component instance.

Syntax:

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

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 is a global object of the browser, and the data stored in it will be cleared when the page is closed. Using this feature, we can share a copy of data across all pages.

Syntax:

// 保存数据到 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();
Copy after login

Note: Key-value pairs are stored in it, which can only be of string type. If you want to store objects, you need to use let objStr = JSON.stringify(obj) to convert into a string and then store it (when using let obj = JSON.parse(objStr) parse it into an object).

Is it troublesome to store objects like this? I recommend a library good-storage, which encapsulates sessionStorage and can directly use its API to store objects

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

11, vuex

I’m not going to introduce how to use this famous vuex here, because it would be too long to write it clearly...

If you don’t plan to develop a large single-page application, using Vuex may be cumbersome and redundant. of. It's true - if your app is simple enough, you probably don't need to use Vuex.

The above is the detailed content of How to pass value to vue component. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

From PHP to Go or Front-end? The suggestions and confusions of reality from experienced people From PHP to Go or Front-end? The suggestions and confusions of reality from experienced people Apr 01, 2025 pm 02:12 PM

Confusion and the cause of choosing from PHP to Go Recently, I accidentally learned about the salary of colleagues in other positions such as Android and Embedded C in the company, and found that they are more...

What are the AI ​​tools for mock interviews? What are the AI ​​tools for mock interviews? Nov 28, 2024 pm 09:52 PM

Mock interview AI tools are valuable tools for efficient candidate screening, saving recruiters time and effort. These tools include HireVue, Talview, Interviewed, iCIMS Video, and Eightfold AI. They provide automated, session-based assessments with benefits including efficiency, consistency, objectivity and scalability. When choosing a tool, recruiters should consider integrations, user-friendliness, accuracy, pricing, and support. Mock interviewing AI tools improve hiring speed, decision quality, and candidate experience.

How to find the right training program for programmers' entry-level skills? How to find the right training program for programmers' entry-level skills? Apr 01, 2025 am 11:30 AM

Programmers' "tickling" needs: From leisure to practice, this programmer friend has been a little idle recently and wants to improve his skills and achieve success through some small projects...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

How to manually trigger the onBlur event of a cell in Avue-crud row editing mode? How to manually trigger the onBlur event of a cell in Avue-crud row editing mode? Apr 04, 2025 pm 02:00 PM

The onBlur event that implements Avue-crud row editing in the Avue component library manually triggers the Avue-crud component. It provides convenient in-line editing functions, but sometimes we need to...

Vue Element uploads large files online errors: How to troubleshoot cross-domain problems and other potential causes? Vue Element uploads large files online errors: How to troubleshoot cross-domain problems and other potential causes? Apr 01, 2025 pm 12:48 PM

Vue Elementel-upload upload file online error reporting and troubleshooting using Vue and Element...

How to monetize programmer skills? From being 'difficult to panic' to taking orders and making money, what are the practical ways? How to monetize programmer skills? From being 'difficult to panic' to taking orders and making money, what are the practical ways? Apr 01, 2025 am 08:27 AM

Programmers’ daily worries and skills monetization: from “I’m so idle” to “helpful” Recently, a programmer friend posted on a forum, expressing “I’m so idle…

Is the convergence of the technology stack the selection of the technology stack? Is the convergence of the technology stack the selection of the technology stack? Apr 02, 2025 pm 04:42 PM

Title: The relationship between technology stack convergence and selection: Does technology stack convergence refer to the selection of technology stack? I saw an article that has a convergence technology stack...