关于javascript:组件通信

8次阅读

共计 1917 个字符,预计需要花费 5 分钟才能阅读完成。

Vue 3 中组件之间的通信形式有很多种,上面我将列举一些罕用的通信形式,包含父传子、子传父、父间接获取子以及应用 pinia 进行状态治理。

  1. 父传子(Props)
    父组件通过 props 将数据传递给子组件。

父组件:

vue

<template>  
  <ChildComponent :message="parentMessage" />  
</template>  

<script>  
import ChildComponent from './ChildComponent.vue';  

export default {  
  components: {ChildComponent},  
  data() {  
    return {parentMessage: 'Hello from Parent'};  
  }  
};  
</script>

子组件:

vue

<template>  
  <div>{{message}}</div>  
</template>  

<script>  
export default {props: ['message']  
};  
</script>
  1. 子传父(Events)
    子组件通过触发自定义事件将数据传递给父组件。

子组件:

vue

<template>  
  <button @click="notifyParent">Notify Parent</button>  
</template>  

<script>  
export default {  
  methods: {notifyParent() {  
      const childMessage = 'Hello from Child';  
      this.$emit('child-event', childMessage);  
    }  
  }  
};  
</script>

父组件:

vue

<template>  
  <ChildComponent @child-event="handleChildEvent" />  
</template>  

<script>  
import ChildComponent from './ChildComponent.vue';  

export default {  
  components: {ChildComponent},  
  methods: {handleChildEvent(childMessage) {console.log(childMessage);  
    }  
  }  
};  
</script>
  1. 父间接获取子(Refs)
    父组件能够应用 ref 间接拜访子组件的实例或 DOM 元素。

父组件:

vue

<template>  
  <ChildComponent ref="childRef" />  
</template>  

<script>  
import ChildComponent from './ChildComponent.vue';  

export default {  
  components: {ChildComponent},  
  mounted() {console.log(this.$refs.childRef); // 拜访子组件实例  
  }  
};  
</script>
  1. Pinia
    Pinia 是一个专为 Vue 3 设计的状态治理库,用于跨组件共享状态。

装置 Pinia:

bash
npm install pinia
应用 Pinia:

首先,在利用的入口文件(如 main.js 或 main.ts)中装置 Pinia 插件:

javascript

import {createApp} from 'vue';  
import {createPinia} from 'pinia';  
import App from './App.vue';  

const app = createApp(App);  
app.use(createPinia());  
app.mount('#app');
而后,在组件中应用 Pinia:

Store:

javascript
// store.js

import {defineStore} from 'pinia';  

export const useStore = defineStore('main', {state: () => ({count: 0}),  
  actions: {increment() {this.count++;}  
  }  
});

组件:

vue

<template>  
  <div>  
    <p>{{count}}</p>  
    <button @click="increment">Increment</button>  
  </div>  
</template>  

<script>  
import {useStore} from './store';  

export default {setup() {const store = useStore();  

    return {  
      count: store.count,  
      increment: store.increment  
    };  
  }  
};  
</script>

这些是在 Vue 3 中罕用的组件通信形式。依据具体的利用场景和需要,你能够抉择适宜的形式来实现组件间的通信。

正文完
 0