vue3以非setup形式使用pinia
时间: 2023-07-14 14:09:29 浏览: 113
如果你想在 Vue 3 中以非 `setup()` 形式使用 Pinia,你可以按照以下步骤进行操作:
1. 安装 Pinia:使用 npm 或者 yarn 安装 Pinia。
使用 npm:
```
npm install pinia
```
使用 yarn:
```
yarn add pinia
```
2. 创建 Pinia 实例:在你的应用程序的入口文件中,创建一个 Pinia 实例。
```javascript
import { createPinia } from 'pinia';
const pinia = createPinia();
```
3. 配置 Vue 3:在应用程序的入口文件中,配置 Vue 3 以使用 Pinia。
```javascript
import { createApp } from 'vue';
import App from './App.vue';
import { pinia } from './pinia';
const app = createApp(App);
app.use(pinia);
app.mount('#app');
```
4. 创建 store:在你的项目中创建一个 store,它将承载你的状态和操作。
```javascript
import { defineStore } from 'pinia';
export const store = defineStore('store', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});
```
5. 在组件中使用 store:在你的组件中导入 store 并使用它。
```vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { store } from './store';
export default {
data() {
return {
count: store.count,
};
},
methods: {
increment() {
store.increment();
},
},
};
</script>
```
通过以上步骤,你可以以非 `setup()` 形式在 Vue 3 中使用 Pinia。记得引入相关的依赖,并按照上述步骤进行操作。希望对你有所帮助!