Pinia组件传值为什么没有变化?

96 阅读1分钟

同事推荐了一个比较香的组件之间传值的方法Pinia 首先安装之后再main.js文件中这样配置

import {createPinia} from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './style.css'
import App from './App.vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import router from './router/index'
const app = createApp(App)
const pinia=createPinia()
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.use(ElementPlus).use(router).use(pinia).mount('#app')

之后创建文件夹stores/index.ts

import { ref, watchEffect } from "vue"

export const useCounterStore = defineStore('counter', () => {
    const isCollapse = ref(false)
    function increment() {
        
        isCollapse.value=!isCollapse.value
    }
    
  
    return { isCollapse, increment }
  })

这里使用的时候注意,使用了ref,当调用时使用结构赋值的方法会获取不到值, 比如const {isCollapse,increment} = useCounterStore(); 正确的使用方法:

const counter  = useCounterStore();
const Collapse = () => {
  counter.increment();
};