vue3+ts项目组件传值

  • 父传子props

  1.父组件

...
<child-com :list="userlist"></child-com>
...
import { ref } from "vue";
import ChildCom from './AcceptChild.vue'
let userlist=ref(['nicoz','nini','coco'])

  2.子组件

复制代码
...
  <li v-for="(item,index) in props.list" :key="index">{{index+1}}--{{item}}</li>
...
const props=defineProps({
  list:{
    type:Array,
    default:()=>[]
  }
})
复制代码
  • 子传父emits

  1.子组件

复制代码
...
<ul>
  <input type="text" v-model="name" placeholder="请在此输入想修改的名字">
  <li v-for="(item,index) in props.list" :key="index">
    {{index+1}}--{{item}}
    <button  @click="changeParentName(index)">修改名字</button>
  </li>
</ul>
...
const emits=defineEmits(['changeName'])
let name=ref("")
function changeParentName(index:number){
  emits('changeName',index,name.value)
}
复制代码

  2.父组件

...
    <child-com :list="userlist" @changeName="changeName"></child-com>
...
function changeName(index:number,name:string){
  userlist.value.splice(index,1,name)
}
  • 父传子或孙(provide,inject)

  1.父组件

...
let username=ref("vivi")
provide('username',username.value)

  2.子组件或子组件的子组件

import { inject } from "vue-demi";
const name=inject('username')
  • 兄弟之间传值(mitt)

  1.命令行安装

npm install mitt --save

  2.声明mitt.js文件

import mitt from "mitt"
export default mitt()

  3-1.在要主动改变兄弟组件值的组件中emit触发事件

...
<button @click="changeSonTwo">changeSonTwo</button>
...
import emitter from '../../mitt'
function changeSonTwo(){
  emitter.emit('changeInfo','I have changed because of sonone')
}

  3-2.在被改变的兄弟组件中监听事件(注意要在onMounted中声明事件)

复制代码
...
import emitter from '../../mitt'

const name = ref('SonTwo')
onMounted(() => {
  emitter.on('changeInfo',(info:any)=>{
    name.value=info
  })
});
复制代码

  3-3.在页面销毁的时候利用off去销毁绑定事件

onUnmounted(()=>{
  emitter.off('changeInfo')
})
  • 其他的还可借助pinia、vuex、cookie、localStorage、sessionStorage等来进行组件之间的通信
posted @   南无、  阅读(3060)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示