Home >Web Front-end >Vue.js >What are the methods for passing values in vue components?
Vue component value transfer method: 1. Use props to transfer value from parent to child; 2. Use "$emit" to transfer value from child to parent; 3. Use EventBus or Vuex for sibling value transfer; 4. Use The "provide/inject" or "$attrs/$listeners" methods perform cross-level value transfer.
The operating environment of this tutorial: windows7 system, vue3 version, Dell G3 computer.
We all know that Vue is a lightweight front-end framework, and its core is Component-based development. Vue is composed of components one by one. Componentization is its essence and one of its most powerful functions. The scopes of component instances are independent of each other, which means that data between different components cannot reference each other.
But in the actual project development process, we need to access the data of other components, so there is a problem of component communication. The relationships between components in Vue are: father-son, brother, and generational. How to implement data transfer for different relationships is what we will talk about next.
That is, the parent component passes value to the child component through attributes, and the child component passes props to receive.
Bind custom properties in the child component tag of the parent component
// 父组件 <user-detail :myName="name" /> export default { components: { UserDetail } ...... }
Just use props (can be an array or an object) in the subcomponent to receive it. Multiple attributes can be passed.
// 子组件 export default { props: ['myName'] } /* props: { myName: String } //这样指定传入的类型,如果类型不对会警告 props: { myName: [String, Number] } // 多个可能的类型 prosp: { myName: { type: String, requires: true } } //必填的的字符串 props: { childMsg: { type: Array, default: () => [] } } // default指定默认值 如果 props 验证失败,会在控制台发出一个警告。 */
The value of the parent component received by the child component is divided into two types: reference type and common type:
Common types: String, Number, Boolean, Null
Reference types: Array, Object (Object)
If the value passed is a simple data type, it can be modified in the child component, and it will not affect the calls from the parent in other sibling components. The value of the component.
The specific operation is to reassign the passed value to a variable in data, and then change that variable.
// 子组件 export default { props: ['myName'], data() { return { name : this.myName // 把传过来的值赋值给新的变量 } }, watch: { myName(newVal) { this.name = newVal //对父组件传过来的值进行监听,如果改变也对子组件内部的值进行改变 } }, methods: { changeName() { this.name = 'Lily' // 这里修改的只是自己内部的值,就不会报错了 }, } }
Note: If watch is not used to monitor the myName value passed by the parent component, the name value in the child component is It will not change with the myName value of the parent component, because name: this.myName in the data only defines an initial value.
#If the value of the reference type is modified in the child component, the parent component will also be modified, because the data is public and others are also referenced The value's subcomponents will also be modified accordingly. It can be understood that the value passed by the parent component to the child component is equivalent to making a copy. The pointer of this copy still points to the one in the parent component, that is, it shares the same reference. So unless there are special needs, don't modify it easily.
1. Subcomponent binds an event , trigger it through this.$emit()
Bind an event in the child component, and define a function for this event
// 子组件 a06555d3f9bc1acdc3ad873256d98d56改变父组件的name65281c5ac262bf6d81768915a4a77ac0 export default { methods: { //子组件的事件 changeParentName: function() { this.$emit('handleChange', 'Jack') // 触发父组件中handleChange事件并传参Jack // 注:此处事件名称与父组件中绑定的事件名称要一致 } } }
Defined in the parent component And bind the handleChange event
// 父组件 07641efda433f8c7133a4cfdcc3be7e37d4dd9c7239aac360e401efe89cbb393 methods: { changeName(name) { // name形参是子组件中传入的值Jack this.name = name } }
2. Through the callback function
First define a callback function in the parent component and pass the callback function
// 父组件 75a731d8f89d34d432d15a53f1e4455b7d4dd9c7239aac360e401efe89cbb393 methods: { callback: function(name) { this.name = name } }
Receive in the child component and execute the callback function
// 子组件 2cea546566374ab655a087de52a59050改变父组件的name65281c5ac262bf6d81768915a4a77ac0 props: { callback: Function, }
3. Access the component instance through $parent / $children or $refs
Both of these are to directly obtain the component instance. After use, you can directly call the component's method or access the data.
// 子组件 export default { data () { return { title: '子组件' } }, methods: { sayHello () { console.log('Hello'); } } }
// 父组件 d477f9ce7bf77f53fbcf36bec1b69b7a cd83204ea32f59c3e11c87bfe8fe7c23 21c97d3a051048b8e55e3c8f199a54b2 3f1c4e4b6b16bbbd69b2ee476dc4f83a export default { created () { // 通过 $ref 来访问子组件 console.log(this.$refs.childRef.title); // 子组件 this.$refs.childRef.sayHello(); // Hello // 通过 $children 来调用子组件的方法 this.$children.sayHello(); // Hello } } 2cacc6d41bbb37262a98f745aa00fbf0
Note: Component communication in this way cannot cross levels.
4. $attrs / $listeners Click here for details
1、还是通过 $emit 和 props 结合的方式
在父组件中给要传值的两个兄弟组件都绑定要传的变量,并定义事件
// 父组件 17fea1a7602fd91b427ad17979409c59 760952284b32fe2031f519d27b0e25d2 export default { data() { return { name: 'John' } }, components: { 'child-a': ChildA, 'child-b': ChildB, }, methods: { editName(name) { this.name = name }, } }
在子组件B中接收变量和绑定触发事件
// child-b 组件 e388a4556c0f65e1904146cc1a846bee姓名:{{ myName }}94b3e26ee717c64999d7867364b1b4a3 023898c17fc87db1696b47c8a39290f3修改姓名65281c5ac262bf6d81768915a4a77ac0 3f1c4e4b6b16bbbd69b2ee476dc4f83a export default { props: ["myName"], methods: { changeName() { this.$emit('changeName', 'Lily') // 触发事件并传值 } } } 2cacc6d41bbb37262a98f745aa00fbf0
// child-a 组件 e388a4556c0f65e1904146cc1a846bee姓名:{{ newName }}94b3e26ee717c64999d7867364b1b4a3 3f1c4e4b6b16bbbd69b2ee476dc4f83a export default { props: ["myName"], computed: { newName() { if(this.myName) { // 判断是否有值传过来 return this.myName } return 'John' //没有传值的默认值 } } } 2cacc6d41bbb37262a98f745aa00fbf0
即:当子组件B 通过 $emit() 触发了父组件的事件函数 editName,改变了父组件的变量name 值,父组件又可以把改变了的值通过 props 传递给子组件A,从而实现兄弟组件间数据传递。
2. 通过一个空 vue 实例
创建一个 EventBus.js 文件,并暴露一个 vue 实例
import Vue from 'Vue'export default new Vue()
在要传值的文件里导入这个空 vue 实例,绑定事件并通过 $emit 触发事件函数
(也可以在 main.js 中全局引入该 js 文件,我一般在需要使用到的组件中引入)
d477f9ce7bf77f53fbcf36bec1b69b7a dc6dce4a544fdca2df29d5ac0ea9906b e388a4556c0f65e1904146cc1a846bee姓名: {{ name }}94b3e26ee717c64999d7867364b1b4a3 023898c17fc87db1696b47c8a39290f3修改姓名65281c5ac262bf6d81768915a4a77ac0 16b28748ea4df4d9c2150843fecfba68 21c97d3a051048b8e55e3c8f199a54b2 3f1c4e4b6b16bbbd69b2ee476dc4f83a import { EventBus } from "../EventBus.js" export default { data() { return { name: 'John', } }, methods: { changeName() { this.name = 'Lily' EventBus.$emit("editName", this.name) // 触发全局事件,并且把改变后的值传入事件函数 } } } 2cacc6d41bbb37262a98f745aa00fbf0
在接收传值的组件中也导入 vue 实例,通过 $on 监听回调,回调函数接收所有触发事件时传入的参数
import { EventBus } from "../EventBus.js" export default { data() { return { name: '' } }, created() { EventBus.$on('editName', (name) => { this.name = name }) } }
这种通过创建一个空的 vue 实例的方式,相当于创建了一个事件中心或者说是中转站,用来传递和接收事件。这种方式同样适用于任何组件间的通信,包括父子、兄弟、跨级,对于通信需求简单的项目比较方便,但对于更复杂的情况,或者项目比较大时,可以使用 vue 提供的更复杂的状态管理模式 Vuex 来进行处理。
3. 使用 vuex →点这里
有时需要实现通信的两个组件不是直接的父子组件,而是祖父和孙子,或者是跨越了更多层级的父子组件,这种时候就不可能由子组件一级一级的向上传递参数,特别是在组件层级比较深,嵌套比较多的情况下,需要传递的事件和属性较多,会导致代码很混乱。
这时就需要用到 vue 提供的更高阶的方法:provide/inject。
这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。查 看 官 网
provide/inject:简单来说就是在父组件中通过provider来提供变量,然后在子组件中通过inject来注入变量,不管组件层级有多深,在父组件生效的生命周期内,这个变量就一直有效。
父组件:
export default { provide: { // 它的作用就是将 **name** 这个变量提供给它的所有子组件。 name: 'Jack' } }
子组件:
export default { inject: ['name'], // 注入了从父组件中提供的name变量 mounted () { console.log(this.name); // Jack } }
注:provide 和 inject 绑定并不是可响应的。即父组件的name变化后,子组件不会跟着变。
如果想要实现 provide 和 inject 数据响应,有两种方法:
// 父组件 dc6dce4a544fdca2df29d5ac0ea9906b 023898c17fc87db1696b47c8a39290f3修改姓名65281c5ac262bf6d81768915a4a77ac0 f6e50660328b0f8ee98e871de7e92ca3 16b28748ea4df4d9c2150843fecfba68 3f1c4e4b6b16bbbd69b2ee476dc4f83a ...... data() { return { name: "Jack" }; }, provide() { return { parentObj: this //提供祖先组件的实例 }; }, methods: { changeName() { this.name = 'Lily' } } 2cacc6d41bbb37262a98f745aa00fbf0
后代组件中取值:
d477f9ce7bf77f53fbcf36bec1b69b7a 3f6cd53913cdb5cc95b1ed83851f3420 64e5601d0a941f4972a2954192bdae18姓名:{{parentObj.name}}ee2bfd64228f824cf6027e0da2815b78 16b28748ea4df4d9c2150843fecfba68 21c97d3a051048b8e55e3c8f199a54b2 3f1c4e4b6b16bbbd69b2ee476dc4f83a export default { inject: { parentObj: { default: () => ({}) } } // 或者inject: ['parentObj'] }; 2cacc6d41bbb37262a98f745aa00fbf0
注:这种方式在函数式组件中用的比较多。函数式组件,即无状态(没有响应式数据),无实例化(没有 this 上下文),内部也没有任何生命周期处理方法,所以渲染性能高,比较适合依赖外部数据传递而变化的组件。
使用 Vue.observable 优化响应式 provide,这个我用的不熟就不说了,可以 → 官方文档
父子通信:父向子传递数据是通过 props,子向父是通过 $emit;通过 $parent / $children 通信;$ref 也可以访问组件实例;provide / inject ;
兄弟通信: EventBus;Vuex;
跨级通信: EventBus;Vuex;provide / inject ;$attrs / $listeners;
相关推荐:《vue.js教程》
The above is the detailed content of What are the methods for passing values in vue components?. For more information, please follow other related articles on the PHP Chinese website!