Home> Web Front-end> Vue.js> body text

What are the methods for passing values in vue components?

青灯夜游
Release: 2023-02-23 11:33:36
Original
34791 people have browsed it

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.

What are the methods for passing values ​​in vue components?

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 isComponent-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.

1. Parent component passes value to child component

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

  • // 父组件  export default { components: { UserDetail } ...... }
    Copy after login
  • 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 验证失败,会在控制台发出一个警告。 */
    Copy after login

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)

Based on vueOne-way data flow, that is, data between components is one-way flow, and child components are not allowed to directly access parent components The passed value is modified, so this operation of directly modifying the value passed by the parent component should be avoided, otherwise the console will report an error.

  • 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 toreassign 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' // 这里修改的只是自己内部的值,就不会报错了 }, } }
    Copy after login

    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.

2. Subcomponent passes value to parent component

1. Subcomponent binds an event , trigger it through this.$emit()

Bind an event in the child component, and define a function for this event

// 子组件  export default { methods: { //子组件的事件 changeParentName: function() { this.$emit('handleChange', 'Jack') // 触发父组件中handleChange事件并传参Jack // 注:此处事件名称与父组件中绑定的事件名称要一致 } } }
Copy after login

Defined in the parent component And bind the handleChange event

// 父组件  methods: { changeName(name) { // name形参是子组件中传入的值Jack this.name = name } }
Copy after login

2. Through the callback function

First define a callback function in the parent component and pass the callback function

// 父组件  methods: { callback: function(name) { this.name = name } }
Copy after login

Receive in the child component and execute the callback function

// 子组件  props: { callback: Function, }
Copy after login

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'); } } }
Copy after login
// 父组件  
Copy after login

Note: Component communication in this way cannot cross levels.

4. $attrs / $listeners Click here for details

三、兄弟组件之间传值

1、还是通过 $emit 和 props 结合的方式

在父组件中给要传值的两个兄弟组件都绑定要传的变量,并定义事件

// 父组件   export default { data() { return { name: 'John' } }, components: { 'child-a': ChildA, 'child-b': ChildB, }, methods: { editName(name) { this.name = name }, } }
Copy after login

在子组件B中接收变量和绑定触发事件

// child-b 组件 

姓名:{{ myName }}

Copy after login
// child-a 组件 

姓名:{{ newName }}

Copy after login

即:当子组件B 通过 $emit() 触发了父组件的事件函数 editName,改变了父组件的变量name 值,父组件又可以把改变了的值通过 props 传递给子组件A,从而实现兄弟组件间数据传递。

2. 通过一个空 vue 实例

创建一个 EventBus.js 文件,并暴露一个 vue 实例

import Vue from 'Vue'export default new Vue()
Copy after login

在要传值的文件里导入这个空 vue 实例,绑定事件并通过 $emit 触发事件函数

(也可以在 main.js 中全局引入该 js 文件,我一般在需要使用到的组件中引入)

 
Copy after login

在接收传值的组件中也导入 vue 实例,通过 $on 监听回调,回调函数接收所有触发事件时传入的参数

import { EventBus } from "../EventBus.js" export default { data() { return { name: '' } }, created() { EventBus.$on('editName', (name) => { this.name = name }) } }
Copy after login

这种通过创建一个空的 vue 实例的方式,相当于创建了一个事件中心或者说是中转站,用来传递和接收事件。这种方式同样适用于任何组件间的通信,包括父子、兄弟、跨级,对于通信需求简单的项目比较方便,但对于更复杂的情况,或者项目比较大时,可以使用 vue 提供的更复杂的状态管理模式 Vuex 来进行处理。

3. 使用 vuex →点这里

四、多层父子组件通信

有时需要实现通信的两个组件不是直接的父子组件,而是祖父和孙子,或者是跨越了更多层级的父子组件,这种时候就不可能由子组件一级一级的向上传递参数,特别是在组件层级比较深,嵌套比较多的情况下,需要传递的事件和属性较多,会导致代码很混乱。

这时就需要用到 vue 提供的更高阶的方法:provide/inject。

这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效查 看 官 网

provide/inject:简单来说就是在父组件中通过provider来提供变量,然后在子组件中通过inject来注入变量,不管组件层级有多深,在父组件生效的生命周期内,这个变量就一直有效。

父组件:

export default { provide: { // 它的作用就是将 **name** 这个变量提供给它的所有子组件。 name: 'Jack' } }
Copy after login

子组件:

export default { inject: ['name'], // 注入了从父组件中提供的name变量 mounted () { console.log(this.name); // Jack } }
Copy after login

注:provide 和 inject 绑定并不是可响应的。即父组件的name变化后,子组件不会跟着变。

如果想要实现 provide 和 inject 数据响应,有两种方法:

  • provide 祖先组件的实例,然后在子孙组件中注入依赖,这样就可以在后代组件中直接修改祖先组件的实例的属性,不过这种方法有个缺点就是这个实例上挂载很多没有必要的东西比如 props,methods
// 父组件  
Copy after login

后代组件中取值:  

 
Copy after login

注:这种方式在函数式组件中用的比较多。函数式组件,即无状态(没有响应式数据),无实例化(没有 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!

Related labels:
source:php.cn
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