State management
- State: Data source that drives the application
- View: Maps state to a view declaratively
- Actions: Responds to state changes caused by user input on the view
Single component flow
Review the communication between components
- The parent component passes values to the child component
- The child component passes values to the parent component
- Pass values between unrelated components
The parent component passes values to the child component
- The child component receives data via props
- The parent component passes values to the child component through the corresponding property
/ / child component
export default{props: {title:String}}/ / the parent component
<child title="My Journey with Vue"/>
Copy the code
The child component passes values to the parent component
/ / child component
handler() {
// Customize events
this.$emit('enlargeText'.'Data to pass')}/ / the parent component<template> <! -- Method 1 --><child @enlargeText="aaa"/><! $event = $event = $event = $event<child @enlargeText="hFontSize += $event"/>
</template>
methods: {
aaa(size) {
// size accepts the passed parameter. }}Copy the code
Pass values between unrelated components
You need to create an EventBus.js, core or custom event
// The code for eventbus.js
import Vue from 'vue'
export default new Vue()
// A component to use
<template>
<div>
<h1>Event Bus Sibling01</h1>
<div class="number" @click="sub">-</div>
<input type="text" style="width: 30px; text-align: center" :value="value">
<div class="number" @click="add">+</div>
</div>
</template>
<script>
import bus from './eventbus'
export default {
props: {
num: Number
},
created () {
this.value = this.num
},
data () {
return {
value: -1}},methods: {
sub () {
if (this.value > 1) {
this.value--
bus.$emit('numchange'.this.value)
}
},
add () {
this.value++
bus.$emit('numchange'.this.value)
}
}
}
</script>
// Another component to use
<template>
<div>
<h1>Event Bus Sibling02</h1>
<div>{{ msg }}</div>
</div>
</template>
<script>
import bus from './eventbus'
export default {
data () {
return {
msg: ' '
}
},
created () {
bus.$on('numchange'.(value) = > {
this.msg = 'You have chosen${value}Goods `}}})</script>
Copy the code
Other common ways
- $root
- $parent
- $childer
- $refs
Review the $ref
Ref and REF
- When you use a ref on a normal HTML tag, you get the DOM
- If you use ref on the component label, you get the component instance
The problem
- Multiple views depend on the same state
- Behaviors from different views need to change the same state