Vue Advanced (vi): data transfer between components
The Vue component scopes are isolated and do not allow direct reference to the parent component's data within the subassembly's template. You must use a specific method to implement data transfer between components.
First, you create a project with the scaffolding tool vue-cli, where App.vue is the parent component, and the Components folder is a child component.
One, the parent component passes data to the child component
In Vue, you can use props to pass data to a subassembly.
Sub-component section:
This is the HTML part of Header.vue , which is a variable defined in data.
If you need to get the value of the logo from the parent component, you need to use props: [' logo ']
After adding elements to the props, you do not need to add variables to the data.
Parent Component section:
When calling a component, use V-bind to bind the value of the logo to the variable logomsg defined in App.vue.
You can then pass the value of the logomsg in the App.vue to Header.vue:
Sub-component pass data to Parent component
Child components pass data primarily through events to the parent component.
Sub-component section:
This is the HTML part of the Login.vue, which passes username to App.vue when the value of <input> is changed.
First declare a method SetUser, and use the Change event to invoke SetUser.
In SetUser, a $emit is used to traverse the Transferuser event and return to This.username.
Where Transferuser is a custom event that functions like a relay, This.username will pass this event to the parent component.
Parent Component section:
In the parent component App.vue, a method GetUser is declared, and the GetUser method is invoked with the Transferuser event to obtain the parameter username passed over from the subassembly.
The parameter msg in the GetUser method is the parameter username passed from the subassembly.
Iii. Sub-component pass data to subcomponents
Vue There is no direct child-passing method, it is recommended that the subcomponents that need to pass data be merged into one component. If you must need child arguments, you can upload them from the parent component and then to the subassembly.
To facilitate development, Vue has launched a State management tool Vuex(detailed in the blog "Vue Advanced (v): First contact with Vuex"), it is easy to implement the parameter transfer between components.