Vue
Rule: This cannot be modified directly in a child componentprops
External data.- But we often make changes in child components
props
To implement this requirement, you can use JS’s publish and subscribe functionality (EventBus). - Look at a simple example: in child components
child
Modify the parent componentfather
In then
The value of the
- But we often make changes in child components
// child.vue
<tamplate>
<div>
{{compData}}
<br />
<button @click="$emit('update:compData', compdata + 1)">n + 1</button>
</div>
</tamplate>
<script>
export default {
props: ["compData"]}</script>
Copy the code
// father.vue
<tamplate>
<div>N: {{n}} of the parent component<br />
<Child :compData.sync="n"/>
<! <Child :compData="n" @update:compData="n = $event"/>
</div>
</tamplate>
<script>
import Child from './child.vue'
export default {
data(){
return {
n: 100}},components: {Child}
}
<script>
Copy the code
Vue
Encapsulates theEventBus
- use
$emit
Define and trigger events, and pass parameters; The event name should be:Update: specifies the name of the monitored data
- use
$event
To get other components$emit
The parameters of the
- use
- Above, modifiers
.sync
It is through$event
Get from other components$emit
Parameter is shorthand for the operation, which is a syntax sugar