Problems with vuejs parent child component communication
- 2021-07-10 18:31:55
- OfStack
Parent and child components can communicate through props:
Definition of component:
1. Create an component class:
var Profile = Vue.extend({
template: "<div>Lily</div>";
})
2. Register an tagnme:
Vue.component("me-profile",Profile);// Global registration
Local registration:
var vm = new Vue({
el: "#todo",
components: {
"my-profile": Profile
},
...
}
Template considerations:
Because Vue is the native DOM, some custom tags may not conform to DOM standard. For example, if you want to customize an tr in table, if inserting my-component directly does not conform to the specification, it should be written as follows:
<table>
<tr is="my-component"></tr>
</table>
There are 1 this in the child component. $parent and this. $root can be used for the method parent component and the following instance. (But not recommended.)
Subcomponents of Vue can communicate with parent components through events. Messages are sent to the parent component through this. $dispatch, and messages are sent to the child component through this. $boardcast, where messages are sent to all parent and child components.
Subcomponents:
props: {
url: {
type: Array,
default: function() {
return []
}
}
} ,
methods: {
add: function() {
this.$dispatch("add", this.input); // This is where the message is sent to the parent component
this.input = "";
}
}
Parent component:
data() {
return {
url: .....
}
} ,
events: {
add: function(input) {
if(!input) return false;
this.list.unshift({
title: input,
done: false
});
}
}