Pass values of parent-child components in vue: props and $emit
Pass value from parent component to child component: through props array:
There are AcceptAndRefuse.vue subcomponents in the parent component of vue-cli Login.vue. First, import into the subcomponent hello, then register the component in components, and then use the component in template to formulate msg information.
//Parent component App.vue <template> <div id="app"> <!-- the router outlet, where all matched components would ber viewed --> <router-link v-bind:to="'/'">Home</router-link> <!-- Create two anchor tags for us and route dynamically so that the page does not need to be reloaded--> <router-link v-bind:to="'/about'">About</router-link> <router-view></router-view> <hello msg-father="dad No comment"></hello> </div> </template> <script> import hello from './components/hello' export default { name: 'app', components:{ hello } } </script> <!-- styling for the component --> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
//Subcomponent. / components/Hello.vue //Receive information through props <template> <div class="hello"> <p>{{msgFather}}</p> </div> </template> <script> export default { name: 'hello', data () { return { } }, props:['msgFather'] } </script> <style scoped> </style>
Subcomponent receives communication
The incoming data is MES family. Vue is converted into MES family, and MES family is written in js
Pass value from child component to parent component: custom event, this.$emit, send information, in parent component
//Sub components: <template> <div class="hello"> <!-- Add one input Input box add keypress Event--> <input type="text" v-model="inputValue" @keypress.enter="enter"> <p>{{mes}}</p> </div> </template> <script> export default { props:['mes'], // Add data and bind user input to inputValue variable to get user input data: function () { return { inputValue: '' } }, methods: { enter () { this.$emit("sendiptVal", this.inputValue) //The child component emits the custom event sendiptVal and carries the value to be passed to the parent component, // If you want to pass many values to the parent component, these values should be listed as parameters, such as this.$emit('valueUp', this.inputValue, this.mesFather); } } } </script>
//Parent component: <template> <div> <p> father</p> <accept-and-refuse :mes=loginJson.animal @sendiptVal='showChildMsg'></accept-and-refuse> </div> </template> <script> import AcceptAndRefuse from '@/components/public/AcceptAndRefuse' export default { data() { return { message:'hello message', loginJson:{ "animal":"dog" } }, mounted(){ }, methods: { components:{ AcceptAndRefuse } } </script> <style> </style>
In vue component, import sub component, registered in components, used in template, router jump