Vue3组件通讯六种方式

源码 2024-9-26 13:37:19 30 0 来自 中国
现在最常用是props/$emit 和 vuex/pinia ,接下来是 provide/inject,其他不发起使用;
现实项目中,简朴父子组件传递采用props/$emit ,涉及全局共享的数据一样平常采用 vuex/pinia 团结存储对象localStorage/sessionStorage使用
1.props/$emit

1.props 单向数据流,父组件向子组件传递数据,不允许子组件修改props
2.支持传递静态大概动态prop,支持多种数据范例,包罗数组,复杂对象
3.支持prop验证范例查抄
静态prop
<blog-post title="My journey with Vue"></blog-post>  //不加冒号动态prop
<blog-post  :author="{    name: 'Veronica',    company: 'Veridian Dynamics'  }"></blog-post>传递对象全部property
post: {  id: 1,  title: 'My Journey with Vue'}<blog-post v-bind="post"></blog-post>范例查抄校验
app.component('my-component', {  props: {    // 底子的范例查抄 (`null` 和 `undefined` 值会通过任何范例验证)    propA: Number,    // 多个大概的范例    propB: [String, Number],    // 必填的字符串    propC: {      type: String,      required: true    },    // 带有默认值的数字    propD: {      type: Number,      default: 100    },    // 带有默认值的对象    propE: {      type: Object,      // 对象或数组的默认值必须从一个工厂函数返回      default() {        return { message: 'hello' }      }    },    // 自界说验证函数    propF: {      validator(value) {        // 这个值必须与下列字符串中的此中一个相匹配        return ['success', 'warning', 'danger'].includes(value)      }    },    // 具有默认值的函数    propG: {      type: Function,      // 与对象或数组的默认值差别,这不是一个工厂函数——这是一个用作默认值的函数      default() {        return 'Default function'      }    }  }})子组件通过自界说事件传递给父组件
<template>  <div>    {{title}}    <event-view @updateTitle="changeTitle"></event-view>  </div></template><script lang="ts">import {defineComponent, ref} from 'vue';import EventView from "@/views/test/EventView.vue";export default defineComponent({  components: {EventView},  setup() {    const title = ref("我是父组件")    return {      title,    };  },  methods:{    changeTitle(val){      this.title = val;    }  },})</script>子组件
<template>  <div><a-button type="primary" @click="$emit('updateTitle','子组件修改了组件')">我是子组件</a-button></div></template><script setup lang="ts">  import {defineExpose, ref} from "vue";  defineEmits(['updateTitle']);</script>2.Vuex/Pinia

vuex 是针对vue的一个状态管理插件,vue3 匹配vuex4,vue2匹配vuex 3的版本,包罗六个核心概念:state getter mutations actions modules

  • actions 可以包罗恣意异步操纵, mutations 是同步操纵,modules为了分割大状态
    重要针对多个组件共享状态时:
  • 多个视图组件依靠同一状态
  • 来自差别的视图的运动须要变更同一状态
1.界说state数据
import { createStore } from 'vuex'interface User{    name:string,    age:number,    status:boolean}const usersModule = {    state: () => ({        users :[{            name: 'test111',            age: 231,            status: true,        }],    }),    getters: {        getActiveUsersstate) => {            return state.users.filter(user => user.status);        },    },    mutations: {        addUser(state,user:User){            state.users.push(user);        }    },    actions: {        addUser(context,user:User){            context.commit('addUser',user)        }    },}export const vueStore = createStore({    modules: {        users: usersModule,    }})

  • 绑定实例全局
import { createApp } from 'vue'import App from './App.vue'const app = createApp(App);app.use(vueStore)···3.组件使用
<template v-for="user in users" :key="user.name">      <div>{{user.name}}|{{user.age}}|{{user.status}}</div></template><script setup lang="ts">    import {computed} from "vue";    import { useStore } from 'vuex'    const store = useStore();    // 在 computed 函数中访问 state    //const users = computed(() => store.state.users),    const users = computed(()=> store.getters.getActiveUsers);//使用getters    const changeMsg = function (){      // 使用 mutation      store.commit('addUser',{name:"dddfas",age:33,status:true});      // 使用 action      store.dispatch('addUser',{name:"111111",age:33,status:true});    }</script>inia 是 Vue 的存储库,也是为了实现跨组件/页面共享状态,但是Pinia 提供了一个更简朴的 API,具有更少的仪式,提供了 Composition-API 风格的 API,最重要的是,在与 TypeScript 一起使用时具有可靠的范例推断支持;
1.创建Pinia实例
import { createApp } from 'vue'import { createPinia } from 'pinia'import App from './App.vue'const pinia = createPinia()const app = createApp(App)app.use(pinia)app.mount('#app')

  • 界说状态数据
import { defineStore } from 'pinia'interface User{    name:string,    age:number,    status:boolean}export const useUsersStore = defineStore({    id: 'todo',    state: () => ({     //界说共享状态users     users :[{         name: 'test1',         age: 23,         status: true,     }]    }),    getters: {   //重要用于读取数据,默认是相应式的        getActiveUsers(state){            return state.users.filter(user => user.status)        }    },    actions: { //重要用于更新数据        addUser(user:User){            this.users.push(user);        }    },})3.在组件/页面中使用
<template v-for="user in users" :key="user.name">      <div>{{user.name}}|{{user.age}}|{{user.status}}</div></template><script setup lang="ts">    import {computed} from "vue";    import {useUsersStore} from "@/store/users";    const usersStore = useUsersStore();    const users = computed(()=>usersStore.getActiveUsers); //使用computed</script>
Vuex与Pinia 默认存储在欣赏器内存中,可以别的存储 好比localStorage/sessionStorage
保举使用Pinia,更加简朴便捷,只提供三个概率state,getters和 actions,听说Pina已经实现了Vuex5 规划的大部门内容
3.provide/inject

重要恰当父子组件,父和子孙组件通讯, 可以看作是长距离的 prop,支持在setup()中使用

  • 父组件不须要知道哪些子组件使用了它 provide 的 property
  • 子组件不须要知道 inject 的 property 来自那里
<template>  <MyMarker /></template><script>import { provide } from 'vue'import MyMarker from './MyMarker.vue'export default defineComponent({  components: {    MyMarker  },  setup() {    provide('location', 'North Pole')    provide('geolocation', {      longitude: 90,      latitude: 135    })  }})</script>使用inject
<!-- src/components/MyMarker.vue --><script>import { inject } from 'vue'export default defineComponent({  setup() {    const userLocation = inject('location', 'The Universe') // The Universe 默认值    const userGeolocation = inject('geolocation')    return {      userLocation,      userGeolocation    }  }})</script>当须要支持相应式注入,只须要在provide值使用ref 或着reactive
... setup() {    const location = ref('North Pole')    const geolocation = reactive({      longitude: 90,      latitude: 135    })    provide('location', location)    provide('geolocation', geolocation)  }...4. 内置属性 ref/$refs $children/$parent $attrs $listeners


  • ref 用于引用子组件,this.$refs 指向子组件
  • $children Vue3 已经废弃不支持了,采用$refs 方式
  • $attrs 现在包罗了全部传递给组件的 attribute,包罗 class 和 style
  • $listeners 对象在 Vue3 中已被移除。事件监听器现在是 $attrs 的一部门
<template>  <div>    {{title}}    <a-button type="primary" @click="changeMsg">父组件</a-button>    <event-view ref="event"></event-view>  </div></template><script lang="ts">import {defineComponent, ref} from 'vue';import EventView from "@/views/test/EventView.vue";export default defineComponent({  components: {EventView},  setup() {    const title = ref("我是父组件")    return {      title,    };  },  methods:{    changeMsg(){      //this.$refs.event.msg = "父组件改变了子组件"  // Object is of type 'unknown'.      (this.$refs.event as any).msg ="父组件改变了子组件";    }  },});</script>子组件:
<template>  <div>{{msg}}<a-button type="primary" @click="changeParent">子组件</a-button></div></template><script lang="ts">import {defineComponent,ref} from "vue";export default defineComponent({  setup(){    let msg = ref('我是子组件');    return {      msg    }  },  methods:{    changeParent(){      this.$parent.title = "子组件改变了父组件"    }  }})</script>$attrs 方式:
<template>  <label>    <input type="text" v-bind="$attrs" />  </label></template><script>export default {  inheritAttrs: false}</script>如果这个组件吸取一个 id attribute 和一个 v-on:close 监听器,那么 $attrs 对象现在将如下所示:
{  id: 'my-input',  onClose: () => console.log('close 事件被触发')}
应该只管制止在<script setup> 使用this,即setup 入口函数引用this
5.localStorage/sessionStorage


  • localStorage与sessionStorage的唯逐一点区别就是localStorage属于永世性存储,而sessionStorage属于当会话竣事的时间,sessionStorage中的键值对会被清空
  • localStorage 办理了cookie存储空间不敷的标题(每条cookie为4k),一样平常欣赏器支持的是5M,差别欣赏器中会有所区别
  • 只支持字符串范例的存储,保举getItem\setItem这两种方法对其举行存取
会话级别是标签级别的,新标签页面sessionStorage继续自之前页面的sessionStorage,但是后续两个页面的sessionStorage是单独控制的
//设置缓存localStorage.setItem('key','value')sessionStorage.setItem('key','value')//获取缓存localStorage.getItem('key')sessionStorage.getItem('key')//删除缓存localStorage.removeItem('key')sessionStorage.removeItem('key')//清空缓存localStorage.clear()sessionStorage.clear()6.eventBus

Vue2.x 使用 EventBus 事件总线举行兄弟组件通讯,而在Vue3中事件总线模式已经被移除,官方发起使用外部的、实现了事件触发器接口的库,例如 mitt 或 tiny-emitter
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:54, Processed in 0.176169 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表