30 Vue3中子组件如何向父组件传值

发布时间:2023年12月22日

概述

在Vue3中,通过emit给父组件传值也经常被用到。

如果需要给父组件传值,emit是最通用的做法,建议重点掌握。

基本用法

我们创建src/components/Demo30.vue,代码如下:

<script setup>
import {ref} from "vue";

// 定义要暴露的值
const count = ref(33)

// 定义要暴露的方法
const emit = defineEmits(["send"])

// 定义触发的方法
function sendToParent() {
  // 通过emit传值
  emit("send", count.value)
}
</script>
<template>
  <div>
    <h3>子组件中的值:{{count}}</h3>
    <button @click="count++">子组件自己修改值</button>
    <button @click="sendToParent">向父组件传递值</button>
  </div>
</template>

接着,我们修改src/App.vue:

<script setup>
import Demo from "./components/Demo30.vue"
import {ref} from "vue";

const childCount = ref(0)

// 接收子组件传递过来的值
function onChildSend(value) {
  alert("子组件传递过来的值:" + value)
  childCount.value = value
}
</script>
<template>
  <h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
  <hr>
  <h3>父组件中的值:{{ childCount }}</h3>
  <Demo @send="onChildSend"/>
</template>

然后,我们浏览器访问:http://localhost:5173/

在这里插入图片描述

完整代码

package.json

{
  "name": "hello",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "vue": "^3.3.8"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.5.0",
    "vite": "^5.0.0"
  }
}

vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
})

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/main.js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

src/App.vue

<script setup>
import Demo from "./components/Demo30.vue"
import {ref} from "vue";

const childCount = ref(0)

// 接收子组件传递过来的值
function onChildSend(value) {
  alert("子组件传递过来的值:" + value)
  childCount.value = value
}
</script>
<template>
  <h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
  <hr>
  <h3>父组件中的值:{{ childCount }}</h3>
  <Demo @send="onChildSend"/>
</template>

src/components/Demo30.vue

<script setup>
import {ref} from "vue";

// 定义要暴露的值
const count = ref(33)

// 定义要暴露的方法
const emit = defineEmits(["send"])

// 定义触发的方法
function sendToParent() {
  // 通过emit传值
  emit("send", count.value)
}
</script>
<template>
  <div>
    <h3>子组件中的值:{{count}}</h3>
    <button @click="count++">子组件自己修改值</button>
    <button @click="sendToParent">向父组件传递值</button>
  </div>
</template>

启动方式

yarn
yarn dev

浏览器访问:http://localhost:5173/

文章来源:https://blog.csdn.net/qq_37703224/article/details/135122894
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。