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
// 子组件 <button>改变父组件的name</button> export default { methods: { //子组件的事件 changeParentName: function() { this.$emit('handleChange', 'Jack') // 触发父组件中handleChange事件并传参Jack // 注:此处事件名称与父组件中绑定的事件名称要一致 } } }
Defined in the parent component And bind the handleChange event
// 父组件 <child></child> 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
// 父组件 <child></child> methods: { callback: function(name) { this.name = name } }
Receive in the child component and execute the callback function
// 子组件 <button>改变父组件的name</button> 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'); } } }
// 父组件 <template> <child></child> </template> <script> export default { created () { // 通过 $ref 来访问子组件 console.log(this.$refs.childRef.title); // 子组件 this.$refs.childRef.sayHello(); // Hello // 通过 $children 来调用子组件的方法 this.$children.sayHello(); // Hello } } </script>
Note: Component communication in this way cannot cross levels.
4. $attrs / $listeners Click here for details
三、兄弟组件之间传值
1、还是通过 $emit 和 props 结合的方式
在父组件中给要传值的两个兄弟组件都绑定要传的变量,并定义事件
// 父组件 <child-a></child-a> <child-b></child-b> export default { data() { return { name: 'John' } }, components: { 'child-a': ChildA, 'child-b': ChildB, }, methods: { editName(name) { this.name = name }, } }
在子组件B中接收变量和绑定触发事件
// child-b 组件 <p>姓名:{{ myName }}</p> <button>修改姓名</button> <script> export default { props: ["myName"], methods: { changeName() { this.$emit('changeName', 'Lily') // 触发事件并传值 } } } </script>
// child-a 组件 <p>姓名:{{ newName }}</p> <script> export default { props: ["myName"], computed: { newName() { if(this.myName) { // 判断是否有值传过来 return this.myName } return 'John' //没有传值的默认值 } } } </script>
即:当子组件B 通过 $emit() 触发了父组件的事件函数 editName,改变了父组件的变量name 值,父组件又可以把改变了的值通过 props 传递给子组件A,从而实现兄弟组件间数据传递。
2. 通过一个空 vue 实例
创建一个 EventBus.js 文件,并暴露一个 vue 实例
import Vue from 'Vue'export default new Vue()
在要传值的文件里导入这个空 vue 实例,绑定事件并通过 $emit 触发事件函数
(也可以在 main.js 中全局引入该 js 文件,我一般在需要使用到的组件中引入)
<template> <div> <p>姓名: {{ name }}</p> <button>修改姓名</button> </div> </template> <script> import { EventBus } from "../EventBus.js" export default { data() { return { name: 'John', } }, methods: { changeName() { this.name = 'Lily' EventBus.$emit("editName", this.name) // 触发全局事件,并且把改变后的值传入事件函数 } } } </script>
在接收传值的组件中也导入 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 数据响应,有两种方法:
- provide 祖先组件的实例,然后在子孙组件中注入依赖,这样就可以在后代组件中直接修改祖先组件的实例的属性,不过这种方法有个缺点就是这个实例上挂载很多没有必要的东西比如 props,methods
// 父组件 <div> <button>修改姓名</button> <child-b></child-b> </div> <script> ...... data() { return { name: "Jack" }; }, provide() { return { parentObj: this //提供祖先组件的实例 }; }, methods: { changeName() { this.name = 'Lily' } } </script>
后代组件中取值:
<template> <div> <p>姓名:{{parentObj.name}}</p> </div> </template> <script> export default { inject: { parentObj: { default: () => ({}) } } // 或者inject: ['parentObj'] }; </script>
注:这种方式在函数式组件中用的比较多。函数式组件,即无状态(没有响应式数据),无实例化(没有 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!

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use
