父子组件通讯
父传子:
父组件代码示例:
<template> <children :list="list"></children> <div> <input v-model="value" type="text" placeholder="请输入" /> <button @click="handleAdd"> 添加 </button> </div> </template> <script setup> import { ref } from 'vue' import Children from '@/views/parentChildCommunicat/parentToChildren/components/children.vue' const list = ref(['JavaScript', 'HTML', 'CSS']) const value = ref('') const handleAdd = () => { list.value.push(value.value) value.value = '' } </script>
子组件代码:
<template> <ul> <li v-for="item in props.list" :key="item">{{ item }}</li> </ul> </template> <script setup> import { defineProps } from 'vue' const props = defineProps({ list: { type: Array, default: () => [] } }) </script>
子传父:
子组件:
<template> <div> <input v-model="value" type="text" placeholder="请输入" /> <button @click="handleAdd"> 添加 </button> </div> </template> <script setup> import { ref, defineEmits } from 'vue' const value = ref('') const emits = defineEmits(['add']) const handleAdd = () => { emits('add', value.value) value.value = '' } </script>
父组件
<template> <ul> <li v-for="item in list" :key="item">{{ item }}</li> </ul> <son @add="add" /> </template> <script setup> import { ref } from 'vue' import Son from './components/son.vue' const list = ref(['JavaScript', 'HTML', 'CSS']) const add = (value) => { list.value.push(value) } </script>
v-model 实现父子组件双向通信
子组件:
<template> <div> <input v-model="value" type="text" placeholder="请输入" /> <button @click="handleAdd"> 添加 </button> </div> </template> <script setup> import { ref, defineEmits, defineProps } from 'vue' const value = ref('') const props = defineProps({ list: { type: Array, default: () => [] } }) const emits = defineEmits(['update:list']) const handleAdd = () => { const arr = props.list arr.push(value.value) emits('update:list', arr) value.value = '' } </script>
父组件
<template> <ul> <li v-for="i in list" :key="i">{{ i }}</li> </ul> <child-components v-model:list="list" /> </template> <script setup> import { ref } from 'vue' import ChildComponents from './components/child-components.vue' const list = ref(['JavaScript', 'HTML', 'CSS']) </script>