There are several ways to communicate between components in Vue, which we summarize here

v-bind

V-bind is a method used by Vue to pass data to its children. In Vue, the parent can pass values to the children as props through V-bind, and the children can get values from the parent as arrays from the props

Of course, if you don’t write V-on, go straight to: the beginning, also v-on consciousness, this is a grammatical sugar of Vue

We tried to implement a parent-child component communication in Vue

/ / requirements: We want to realize communication between a group of components in VUE. The parent component Fa passes num to the child component Son, and Son can modify the value through its own spend method and render it to the page. Fa.vue <template> <div> father <Son :num="num" :spend="(value)=>{spend(value)}"/> </div> </template> <script> import Son from "./Son"; export default { components:{Son}, name: "Fa", data(){ return { num:100 } }, methods:{ spend(value){ return this.num -= value } } } </script> Son.vue <template> <div> son have father's money is {{num}} <button @click="spend(10)">spend</button> </div> </template> <script> export default { props:["num","spend"], name: "Son", } </script>Copy the code

The effect is as follows:



But this method is too cumbersome, so Vue gives you a syntactic sugar called.sync, which is written in the code below

Fa.vue <template> <div> father <Son :num.sync="num"/> </div> </template> Son.vue <template> <div> son have father's Money is {{num}} $emit; // Add $emit; update: XXX; < button@click ="$emit('update:num',num-10)"> Spend </button> </div> </template>Copy the code

What if the parent components of Vue are far apart? Provide /inject, here’s how they are used:

// The above requirement is slightly modified, if it is his grandchild component, I need the value num, Father {export default{provide:{num:100}} Father {export default{provide:{num:100}} grandSon{export default{inject:["num"]}Copy the code

However, this method currently appears to have two drawbacks. One is that it must be a descendant of the parent component, and the second is that it cannot pass in the local this value as an argument. For now, this will be done after learning Vuex