Home>Article>Web Front-end> How to transfer values between vue2.0 components? A brief analysis of component transmission methods

How to transfer values between vue2.0 components? A brief analysis of component transmission methods

青灯夜游
青灯夜游 forward
2022-07-05 16:21:47 1749browse

vueHow to transfer values between components? The following article will introduce you to the component transmission method in vue2.0. I hope it will be helpful to you!

How to transfer values ​​between vue2.0 components? A brief analysis of component transmission methods

Component-based development is an important development method in VUE. When each component is developed separately, there will inevitably be a problem of value transfer between components. (Learning video sharing:vuejs video tutorial)

props passes prop value

propsThe value passed is between parent and child components The most common way to pass values indirectly is to add the data you want to transfer to the subcomponent and obtain the data through props when referencing the subcomponent.

Parent.vue  Child.vue export default { // 数组写法 props: ["child-data"]; // 对象写法 props: { child-data: { type: String, require: true, // 是否必须 default: "默认值", // 设置默认值 validator(val) { return true; }, // 设置值的 验证 ,验证该值是否符合(true) } } }

When we usepropsto complete the parent component passing data to the child component, in this case, the data obtained by the child component from the parent component cannot be processed.Change, you must use$emitto modify the transmitted value.

$emit passes value to modify prop

#propscan be used in conjunction with$emitto achieve the communication between parent and child components Passing by value means that the child component$emithandles the event of the parent component so that the child component can modify the data in the parent component and pass the value to the parent component.

Parent.vue  methods: { changeChild(val) { console.log(val); // 子组件传递过来的更改了的新值 this.childData = val; } } Child.vue methods: { handleChildData() { this.$emit("change-child", new-child-data); } }

Not onlyprops, but also throughmodel syntax sugarto achieve value transfer between parent and child components, and such a value transfer method is particularly cumbersome and will cause A lot of inconvenience.

v-model passes prop value

modelYou can replace the specific value with$emit byvalueComplete the value transfer between parent and child components, the writing method is slightly different.

Parent.vue  Child.vue export default { props: ["value"], // value methods: { handleChildData() { this.$emit("input", new-child-data); } } }

You can also pass values by definingmodel(no need to usepropsto obtain data).

Parent.vue  Child.vue export default { model: { prop: "child-data", // 重新取名 event: "change-child-data", }, methods: { handleChildData() { this.$emit("change-child-data", new-child-data); } } }

However,v-modelcan only handle oneprop. If we want to handle multipleprop, it cannot be used.

.sync implements multi-prop value passing

Parent.vue  Child.vue export default { props: ["child-data"], methods: { handleChildData() { this.$emit("update:child-data", new-child-data); } } }

However, in VUE3,syncwill no longer need to be used,v-modelwill support multipleproppassed values.

In addition to usingpropto pass values, you can also userefto point to the component to obtain the properties or methods in the subcomponent.

ref Sub-component call

points to the component throughref, which can be obtained by calling the properties or methods in the component.

Parent.vue  export default { mounted() { const child = this.$refs.child; console.log(child.childData); child.handleChild("handle-child-data"); } } Child.vue export default { data() { return { childData: "child-data", } }, methods: { handleChild(val) { console.log(val); } } }

Not only can you userefto obtain child component data, but you can also usechildren&parentPass data from parent-child components.

$children&$parent

##$childrencan get a parent component An array of all subcomponents through which the properties or methods in the subcomponent you want to operate can be obtained.

$parentYou can get the parent component (object) and call it.

Parent.vue this.$children[0].handleChild("change-child[0]-data"); Child.vue this.$parent.handleParent("change-parent-data");
But the first few methods (

prop & ref) can only realize the value transfer between parent and child components, and cannot complete the communication between parent components and components with multi-layer nested relationships. Passing by value, if implemented, will be very troublesome, causing code redundancy and extremely low reusability.

We can use other methods (

attrs&listeners, provide&inject, eventBus) to realize the connection between multi-layer nested components and parent components passed value.

$attrs&$listeners

$attrsContains the incoming The data of the grandson component (exceptproppassed properties,class,style). Passv-bind="$attrscan be passed into the grandson component.

$listenerscontains allv-on## in the parent component #Events (except those containing the.nativedecorator). Pass the methods in the parent component to the grandchild component throughv-on="$listeners.

<sun-child v-bind="$attrs" v-on="$listeners"></sun-child>

provide & inject

provide

Can provide required data or methods to descendant components (no matter how many levels of nested components).

inject

You can obtain the data or methods provided in any parent component and use them directly.

Parent.vue provide() { return { parent-data: "parent-data", handleParent: this.handleParent, } }, methods: { handleParent() {}, } Sun-Child.vue inject: ["parent-data", handleParent"],

但是provide & inject是不可控的,因为这个里面传递的数据并不是响应式的(其中一个数据改变,并不会影响另外的),当某个嵌套组件使用某个传输的值的时候并不能追溯到是哪个父组件,所以,这种方式并不是特别可取。

eventBus 中央事件总线

eventBus,顾名思义,中央事件总线,可以通过其实现各个层套的组件之间的传值,包括兄弟组件。

我们可以通过将其抽离出来成一个单独的js文件(Bus.js),挂载到全局(Vue.prototype.$bus)或者按需引入,又或者是存入到根对象的data上。

// 以按需引入的情况为例 import Bus from 'Bus.js' Bus.$emit("handleBus", "自定义事件"); // 向外部传递数据 Bus.$on("handleBus", data => {}); // 触发事件,获取数据 Bus.$off("handleBus"); // 取消对自定义事件的监听

但是这些方法也只是适用于小范围内的数据使用较少的组件中,需要传递的数据过多的话,维护会很麻烦,且可复用性也极低。当数据传递量大的时候,建议使用vuex状态管理器常用)。

Tips

其实也可以通过插槽进行父子组件的值传递,不过插槽的作用不止如此,但是如果有遇到使用插槽更方便的情况的时候可以使用插槽slot

【相关视频教程推荐:web前端

The above is the detailed content of How to transfer values between vue2.0 components? A brief analysis of component transmission methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete