面试题答案
一键面试- 安装Pinia:
在Vue项目中,如果尚未安装Pinia,通过npm或yarn进行安装。
npm install pinia # 或者 yarn add pinia
- 创建Pinia仓库:
在项目合适目录(例如
stores
目录)下创建一个Pinia仓库文件,比如store.js
。import { defineStore } from 'pinia' export const useSharedStore = defineStore('shared', { state: () => ({ sharedString: '' }), actions: { updateSharedString(newStr) { this.sharedString = newStr } } })
- 在组件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>
- 在组件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)