pinia 在template中引用

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

pinia 在template中引用
Pinia 是一个状态管理库,它与 Vue.js 一起使用,用于在 Vue.js 应用中管理状态。

在 Pinia 中,你可以定义一个 store,并在 Vue 组件中通过
`useStore` 函数来访问它。

要在 template 中引用 Pinia store,你可以使用`ref` 函数和 `computed` 属性。

下面是一个示例,展示了如何在 template 中引用 Pinia store:
首先,安装 pinia:
```bash
npm install pinia@next
```
然后,创建一个 Pinia store:
```javascript
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
}
}
});
```
在 Vue 组件中,使用 `useStore` 函数来获取 store 的实例:```javascript
// src/components/Counter.vue
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script>
import { useCounterStore } from '../stores/counter';
export default {
setup() {
const counterStore = useCounterStore();
return {
count: counterStore.count, // 将 store 中的状态映射到组件的data 属性上
increment: counterStore.increment, // 将 store 中的 action 映射到组件的方法上
decrement: counterStore.decrement
};
}
};
</script>
```
在上面的示例中,我们通过 `useCounterStore` 函数获取了 `counter` store 的实例,并将其存储在 `counterStore` 变量中。

然后,我们将 `count` 状态和 `increment`、`decrement` actions 分别映射到组件的 `data` 属性和方法上。

这样,我们就可以在 template 中直接使用 `count`、`increment` 和`decrement` 了。

相关文档
最新文档