MST

星途 面试题库

面试题:Vue中Pinia如何在兄弟组件间实现跨组件通信

请描述在Vue项目中,使用Pinia进行兄弟组件之间跨组件通信的具体步骤和关键代码。假设存在组件A和组件B,需要在这两个兄弟组件间传递一个字符串数据。
49.9万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 安装Pinia: 在Vue项目中,如果尚未安装Pinia,通过npm或yarn进行安装。
    npm install pinia
    # 或者
    yarn add pinia
    
  2. 创建Pinia仓库: 在项目合适目录(例如stores目录)下创建一个Pinia仓库文件,比如store.js
    import { defineStore } from 'pinia'
    export const useSharedStore = defineStore('shared', {
        state: () => ({
            sharedString: ''
        }),
        actions: {
            updateSharedString(newStr) {
                this.sharedString = newStr
            }
        }
    })
    
  3. 在组件A中使用: 引入并使用Pinia仓库来更新数据。假设组件A是一个模板组件,在script标签内:
    <template>
        <div>
            <input v-model="inputValue" type="text" placeholder="输入要传递的字符串">
            <button @click="sendData">发送数据</button>
        </div>
    </template>
    <script setup>
    import { useSharedStore } from './stores/store.js'
    const sharedStore = useSharedStore()
    const inputValue = ref('')
    const sendData = () => {
        sharedStore.updateSharedString(inputValue.value)
    }
    </script>
    
  4. 在组件B中使用: 引入Pinia仓库来获取数据。同样假设组件B是一个模板组件,在script标签内:
    <template>
        <div>
            <p>接收到的字符串: {{ receivedString }}</p>
        </div>
    </template>
    <script setup>
    import { useSharedStore } from './stores/store.js'
    const sharedStore = useSharedStore()
    const receivedString = computed(() => sharedStore.sharedString)
    </script>
    

关键代码总结:

  • Pinia仓库定义
    export const useSharedStore = defineStore('shared', {
        state: () => ({
            sharedString: ''
        }),
        actions: {
            updateSharedString(newStr) {
                this.sharedString = newStr
            }
        }
    })
    
  • 组件A更新数据
    const sendData = () => {
        sharedStore.updateSharedString(inputValue.value)
    }
    
  • 组件B获取数据
    const receivedString = computed(() => sharedStore.sharedString)