Article directory
foreword
- The vue version is greater than >3.2
- Using setup syntax sugar
1. Preliminary preparation
2. Initialize the project
- Vue/cli scaffolding initializes the vue3 project
- Create a new subcomponent child.vue under components
- App.vue parent component introduces child component child.vue
1. Pass value from parent component to child component
The code is as follows:
parent component App.vue:
<Child :num="12" name="武林外传"></Child>
Child component child.vue:
//定义接收属性
import {
defineProps } from "vue";
// 定义从父组件接收的属性
const props = defineProps({
num: Number,
name: String,
});
//template显示:
<div>收到父组件的值:{
{
props.num }},{
{
props.name }}</div>
result:
2. Pass the value from the child component to the parent component
The code is as follows (example):
child.vue:
// 定义触发事件,向父组件传值
import {
defineEmits } from "vue";
const emits = defineEmits(["emit1", "emit2"]);
//创建两个button事件,用于触发发送事件
<button @click="add1">发送数据一给父组件</button>
<button @click="add2">发送数据二给父组件</button>
//各自对应的触发方法
const add1 = () => {
emits("emit1", 1);//点击add1则触发了事件emit1,同时携带参数‘1’给接收emit1事件的父组件
};
const add2 = () => {
emits("emit2", 2);//点击add2则触发了事件emit2,同时携带参数‘2’给接收emit1事件的父组件
};
Parent component App.vue:
<Child @emit1="receive1" @emit2="receive2"></Child>
//定义用于接收emit1和emit2触发事件的方法
const receive1 = (e) => {
console.log("收到从子组件addNum传来的:", e);
};
const receive2 = (e) => {
console.log("收到从子组件chuyi传来的:", e);
};
Click to view the results:
3. Complete code
Subcomponent child.vue:
<template>
<div>
<div>收到父组件的值:{
{
props.num }},{
{
props.name }}</div>
<button @click="add1">发送数据一给父组件</button>
<br />
<button @click="add2">发送数据二给父组件</button>
</div>
</template>
<script setup>
import {
defineProps, defineEmits } from "vue";
// 定义触发事件,向父组件传值
const emits = defineEmits(["emit1", "emit2"]);
// 定义从父组件接收的属性
const props = defineProps({
num: Number,
name: String,
});
// console.log(props);
// 子组件向父组件传递参数 触发父组件的addNum方法,同时传入参数2;通过注册emits,同时触发对应的方法名,传入参数
const add1 = () => {
emits("emit1", 1);
};
const add2 = () => {
emits("emit2", 2);
};
</script>
Parent component App.vue:
<template>
<!--可以没有根标签 div -->
<div class="c">
<Child @emit1="receive1" @emit2="receive2" :num='num' name="武林外传"></Child>
</div>
</template>
<script setup>
import Child from "./components/child.vue";
import {
ref } from "vue";
const num = ref(12);
const receive1 = (e) => {
console.log("收到从子组件addNum传来的:", e);
num.value *= e;
};
const receive2 = (e) => {
console.log("收到从子组件chuyi传来的:", e);
num.value /= e;
};
</script>
<style scope>
</style>
Summarize
Simply record Vue3's parent-child component value passing under the setup syntactic sugar