赞
踩
Nuxt跨页面、跨组件全局状态共享可使用 useState(支持Server和Client )
useState<T>(init?: () => T | Ref<T>): Ref<T>
useState<T>(key: string, init?: () => T | Ref<T>): Ref<T>
注意:
使用步骤:
composables/useCounter.ts
export default function () {
return useState("counter", () => 100); // Ref
}
// export const useCounter = () => {
// return useState("counter", () => 100);
// };
<template>
<div class="home">
<div>{{ counter }}</div>
<button @click="addCounter">+1</button>
</div>
</template>
<script setup>
// counter -> Ref
const counter = useCounter();
function addCounter() {
counter.value++;
}
</script>
安装:
npm install @pinia/nuxt –-save
npm install pinia –-save
如有遇到pinia安装失败,可以添加 --legacy-peer-deps 告诉 NPM 忽略对等依赖并继续安装。或使用yarn
修改配置:
nuxt.config.ts
export default defineNuxtConfig({
// 这里是配置Nuxt3的扩展的库
modules: ["@pinia/nuxt"],
});
使用步骤:
store/home.ts
import { defineStore } from "pinia"; export interface IState { counter: number; homeInfo: any; } export const useHomeStore = defineStore("home", { state: (): IState => { return { counter: 0, homeInfo: {}, }; }, actions: { increment() { this.counter++; }, async fetchHomeData() { const url = "http://codercba.com:9060/juanpi/api/homeInfo"; const { data } = await useFetch<any>(url); console.log(data.value.data); this.homeInfo = data.value.data; }, }, });
使用
<template> <div class="category"> <div>{{ counter }}</div> <button @click="addCounter">+1</button> <button @click="getHomeInfo">fetchHomeInfoData</button> </div> </template> <script setup lang="ts"> import { storeToRefs } from "pinia"; import { useHomeStore } from "~/store/home"; const homeStore = useHomeStore(); const { counter, homeInfo } = storeToRefs(homeStore); function addCounter() { homeStore.increment(); } function getHomeInfo() { homeStore.fetchHomeData(); } </script>
共同点:
Pinia优势:
安装:
npm install element-plus --save
npm install unplugin-element-plus --save-dev
配置Babel对EP的转译
配置自动导入样式
nuxt.config.ts
import ElementPlus from "unplugin-element-plus/vite";
export default defineNuxtConfig({
// dev build
build: {
// 使用 Babel 进行语法转换
transpile: ["element-plus/es"],
},
vite: {
// 配置自动导入样式
plugins: [ElementPlus()],
},
});
使用:
<template>
<div>
<el-button type="danger" size="large">我是button</el-button>
</div>
</template>
<script setup lang="ts">
// 需要手动导入
import { ElButton } from "element-plus";
</script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。