The common way to achieve the parent component value
In common mode, the parent component uses custom attributes to pass values to the child component and receives events through custom events. Child components receive data via props, and child components pass custom events to parent components via $emit.
The implementation code is as follows:
Child components:
<template> <div> I am a child component: <input type="text" :value="msg" @input="changeValFn" /> </div> </template> <script> export default { name: 'child', props: ['msg'], methods: { changeValFn(e) { this.$emit('changeMsg', e.target.value) }, }, } </script>Copy the code
The parent component:
<template> <div class="parent"> <h1> {{ msg }}</h1> <child :msg="msg" @changeMsg="changeMsgFn"></child> </div> </template> <script> import child from './child' export default { name: 'parent', components: { child, }, data() { return { msg: 'hello! ', } }, methods: { changeMsgFn(value) { this.msg = value }, }, } </script>Copy the code
The V-Model implements parent-child transmission
V-model is syntax sugar. V-model is equivalent to providing the :value attribute and @input event to an input box. However, if you need to provide the value and input event every time you use an input box, it is troublesome to use v-Model.
Implementation code:
Child components:
<template> <div> I am a child component: <input type="text" :value="value" @input="changeValFn" /> </div> </template> <script> export default { name: 'child', props: ['value'], methods: { changeValFn(e) { this.$emit('input', e.target.value) }, }, } </script>Copy the code
The parent component:
<template> <div class="parent"> <h1> {{ msg }}</h1> <child v-model="msg"></child> </div> </template> <script> import child from './child' export default { name: 'parent', components: { child, }, data() { return { msg: 'hello! ', } }, } </script>Copy the code
In VUe3.0, parent and child components pass values
Vue3.0 deprecated.sync and replaced all parts that used.sync with v-model:
<ChildComponent :title.sync="pageTitle" /> <! --> <ChildComponent v-model:title="pageTitle" />Copy the code
The implementation code is as follows:
Child components:
<template> <label> I am a child component: </label> <input type="text" :value="msg" @input="changeValFn" /> </template> <script> export default { name: 'child', props: ['msg'], methods: { changeValFn(e) { this.$emit('update:msg', e.target.value) }, }, } </script>Copy the code
The parent component:
<template> <h1> I am the parent component: {{ msg }}</h1> <child v-model:msg="msg"></child> </template> <script> import child from './components/child' export default { name: 'App', components: { child, }, data() { return { msg: 'hello! ', } }, } </script>Copy the code
Note:
Make sure to change the name of prop and event to modelValue and Update :modelValue respectively for all v-Models with no parameters in the sub-component