Commonly used child components in vue2 change the value of the parent component
- Use $emit in the child component to emit a custom event to the parent component, then define this method in the methods of the parent component, and do data processing in the method body.
parent component:
<template>
<Children :count="count" @changeCount="addCount" />
</template>
<script lang="ts">
import Children from './components/Children.vue'
export default {
components: {
Children
},
data () {
return {
count: 0
}
},
methods: {
addCount(params) {
this.count += params
}
}
}
</script>
Subassembly:
<template>
<h1>{
{ count }}</h1>
<button @click="addCount">点击改变父组件的值</button>
</template>
<script lang="ts">
export default {
props: {
count: Number
},
methods: {
// 通过方法请求给父组件传值
addCount() {
this.$emit('changeCount', 1)
}
}
}
</script>
- You can also use the .sync modifier to directly update the value passed from the parent component in the child component.
parent component:
<template>
<div id="app">
<Children :count.sync="count" />
</div>
</template>
<script>
import Children from './components/Children.vue'
export default {
components: {
Children
},
data() {
return {
count: 0
}
}
}
</script>
Subassembly:
<template>
<div class="hello">
<h1>{
{ count }}</h1>
<button @click="addCount">点击改变父组件的值</button>
</div>
</template>
<script>
export default {
props: {
count: Number
},
methods: {
addCount() {
this.$emit('update:count', this.count + 1)
}
}
}
</script>
Commonly used child components in vue3 change the value of the parent component
- Use the sync parent component in the form of v-model in vue3
:
<template>
<Children v-model:count="count" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Children from './components/Children.vue'
const count = ref<number>(0)
</script>
Subassembly:
<template>
<h1>{
{ count }}</h1>
<button @click="addCount">点击改变父组件的值</button>
</template>
<script setup lang="ts">
import { ref, defineProps, reactive, onMounted, watch } from 'vue'
const props = defineProps({
count: {
type: Number,
required: true,
},
})
const emit = defineEmits(['update:count'])
const addCount:() => void = () => {
emit('update:count', props.count + 1)
}
</script>