Home >Web Front-end >Front-end Q&A >How to pass value to vue component
Value passing method: 1. Use props to pass from parent to child; 2. Pass from child to parent, you need to customize the event, use "this.$emit('event name')" to trigger it in the child component, and Use "@event name" in the parent to listen; 3. Between brothers, use the public parent element as a bridge, combine parent and child props to pass parameters, and child and parent custom events; 4. Use routes to pass values; 5. Use $ref to pass values; 6 , use dependency injection to pass to descendants and great-grandchildren; 7. Use $attrs; 8. Use $listeners intermediate events; 9. Use $parent to pass, etc.
The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.
This article will talk about the 10 ways to transfer values in Vue components. There are five or six commonly used methods. Let’s start with a summary picture:
Define a props in the child component, that is, props:['msg'], msg can be Objects can also be basic data types
If you want to define a default value, i.e. props:{msg: {type: String, default: 'hello world'}},
If the default value is an object type :props: { msg: { type: Object, default: () => { return { name: 'dan_seek' } } }}
It should be noted that this kind of value transfer is one-way. The value of the parent component cannot be changed (except for reference types, of course); and if the value of props is modified 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:['msg'], data() { return { myMsg:this.msg } }, methods: {} } </script>
Parent.vue
<template> <div class="parent"> <Children :msg="message"></Children> </div> </template> <script> import Children from '../components/Children' export default { name: 'Parent', components: { Children }, data() { return { message:'hello world' } }, } </script>
You need to use custom events here, use this.$emit('myEvent') in the child component to trigger, and then use @myEvent in the parent component to listen
Children.vue
<template> <div class="parent"> 这里是计数:{{parentNum}} <Children-Com @addNum="getNum"></Children-Com> </div> </template> <script> import ChildrenCom from '../components/Children' export default { name: 'Parent', components: { ChildrenCom }, data() { return { parentNum: 0 } }, methods:{ // childNum是由子组件传入的 getNum(childNum){ this.parentNum = childNum } } } </script>
Parent.vue
<template> <div> 这里是计数:{{parentNum}} <children-com></children-com> </div></template><script> import ChildrenCom from '../components/Children' export default { name: 'Parent', components: { ChildrenCom }, data() { return { parentNum: 0 } }, methods:{ // childNum是由子组件传入的 getNum(childNum){ this.parentNum = childNum } } }</script>
emit's triggering and monitoring capabilities define a public event bus eventBus, through which we can pass values to any component through it as an intermediate bridge. And through the use of eventBus, you can deepen your understanding of emit.
EventBus.jsimport Vue from 'vue' export default new Vue()Children1.vue
<template> <section> <div @click="pushMsg">push message</div> <br> </section> </template> <script> import eventBus from './EventBus' export default { name: "Children1", components: {}, data() { return { childNum:0 } }, methods: { pushMsg(){ // 通过事件总线发送消息 eventBus.$emit('pushMsg',this.childNum++) } } } </script>Children2.vue
<template> <section> children1传过来的消息:{{msg}} </section> </template> <script> import eventBus from './EventBus' export default { name: "Children2", components: {}, data() { return { msg: '' } }, mounted() { // 通过事件总线监听消息 eventBus.$on('pushMsg', (children1Msg) => { this.msg = children1Msg }) } } </script>Parent.vue
<template> <div class="parent"> <Children1></Children1> <Children2></Children2> </div> </template> <script> import Children1 from '../components/Children1' import Children2 from '../components/Children2' export default { name: 'Parent', 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
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 APlease note the difference between router and routeii. Use colons to pass values
Configure the following route:{ path: '/b/:name', name: 'b', component: () => import( '../views/B.vue') },Can be obtained through this.$route.params.name on page B The value of the name passed in by the route
iii. Use the parent-child component to pass the value
Since router-view itself is also a component, we also You can 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, you cannot directly obtain the latest type value directly in the mounted hook of the sub-page, but use watch.<router-view></router-view>
// 子页面 ...... props: ['type'] ...... watch: { type(){ // console.log("在这个方法可以时刻获取最新的数据:type=",this.type) }, },
<template> <section> 传过来的消息:{{msg}} </section> </template> <script> export default { name: "Children", components: {}, data() { return { msg: '', desc:'The use of ref' } }, 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 '../components/Children' export default { name: 'parent', components: { Children, }, methods:{ pushMsg(){ // 通过这个ID可以访问子组件的方法 this.$refs.children.updateMsg('Have you received the clothes?') // 也可以访问子组件的属性 console.log('children props:',this.$refs.children.desc) } }, } </script>
provide: function () { return { getName: this.getName() } }# The ##provide option allows 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 parent component into the current instance Data/method: <pre class="brush:js;toolbar:false;">inject: [&#39;getName&#39;]</pre>
Parent.vue
<template> <div class="parent"> <Children></Children> </div> </template> <script> import Children from '../components/Children' export default { name: 'Parent', components: { Children, }, data() { return { name:'dan_seek' } }, provide: function () { return { getName: this.name } }, } </script>
Children.vue
父组件传入的值:{{getName}} <script> export default { name: "Children", components: {}, data() { return { } }, inject: [&#39;getName&#39;], } </script>
<template> <section> <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent> </section> </template> <script> import Parent from './Parent' 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 './Children' export default { name: "Parent", components: { Children }, // 父组件接收了name,所以name值是不会传到子组件的 props:['name'], 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:['sex','age','hobby','name'], data() { return {} }, methods: { sayKnow(){ this.$emit('sayKnow','我知道啦') } }, mounted() { } } </script>Display results
父组件收到 祖父的名字:grandParent 子组件收到 祖父的名字: 祖父的性别:男 祖父的年龄:88 祖父的爱好:code
语法:
// 获父组件的数据 this.$parent.foo // 写入父组件的数据 this.$parent.foo = 2 // 访问父组件的计算属性 this.$parent.bar // 调用父组件的方法 this.$parent.baz()
于是,在子组件传给父组件例子中,可以使用this.$parent.getNum(100)传值给父组件。
sessionStorage 是浏览器的全局对象,存在它里面的数据会在页面关闭时清除 。运用这个特性,我们可以在所有页面共享一份数据。
语法:
// 保存数据到 sessionStorage sessionStorage.setItem('key', 'value'); // 从 sessionStorage 获取数据 let data = sessionStorage.getItem('key'); // 从 sessionStorage 删除保存的数据 sessionStorage.removeItem('key'); // 从 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
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!