先行知识
- 【vue】导入组件
- 【vue】defineProps 传数据 父传子
传值流程
App.vue
<template>
<Header @getWeb="emitsGetWeb" @userAdd="emitsUserAdd"/>
<hr />
<p>web.name: {{ web.name }}</p>
<p>web.url: {{ web.url }}</p>
<p>user: {{ user }}</p>
</template>
<script setup>
import { ref, reactive } from "vue";
import Header from "./components/Header.vue";
//响应式数据
const web = reactive({
name: "1234567890",
url: "https://www.1234567890.com",
});
let user = ref(0);
const emitsGetWeb = (data) => {
console.log(data);
web.name = data.name;
web.url = data.url;
}
const emitsUserAdd = (data) => {
console.log(data);
user.value += data;
console.log(user.value);
}
</script>
<style lang="scss" scoped></style>
Header.vue
<template>
<h2>header</h2>
<button @click="userAdd">添加用户</button>
</template>
<script setup>
const emits = defineEmits(['getWeb', "userAdd"])
emits("getWeb", { name: "Header Name" , url: "Header Url"})
const userAdd = () => {
emits("userAdd",1)
}
</script>
<style lang="scss" scoped></style>
参考
https://www.bilibili.com/video/BV1nV411Q7RX