阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
.value 访问/修改,模板中无需写 .valueimport { ref } from 'vue'
const count = ref(0)
count.value++const count = ref(0)
const add = () => count.value++
const double = computed(() => count.value * 2)import { computed } from 'vue'
const doubleCount = computed(() => count.value * 2)async:标记函数为异步函数,默认返回 Promiseawait:只能在 async 函数内使用,等待异步操作完成后再继续执行async function loadData() {
const res = await fetch('/api/data')
const data = await res.json()
}import { onMounted } from 'vue'
onMounted(() => {
console.log('组件已挂载')
loadData()
})<ul>:无序列表标签,包裹列表整体<li>:列表项标签,代表列表中的每一项<ul>
<li>列表项1</li>
<li>列表项2</li>
</ul>// 对象解构
const obj = { name: '张三', age: 18 }
const { name, age } = obj
// 数组解构
const arr = [10, 20]
const [a, b] = arrimport { storeToRefs } from 'pinia'
const useStore = defineStore('storeId', {
state: () => ({ count: 0 })
})
const store = useStore()
const { count } = storeToRefs(store)const useStore = defineStore('storeId', {
actions: {
async fetchData() {
const res = await fetch('/api/data')
this.data = await res.json()
}
}
})Pinia 是用来做什么的? Pinia 是 Vue 的全局状态管理工具,用于多个组件之间共享和管理数据。
Pinia 中还需要 mutation 吗? 不需要,Pinia 去掉了 mutation 概念,可直接修改 state 数据。
Pinia 如何实现 getter? Pinia 中可直接使用 computed 实现类似 Vuex 中 getter 的功能,或在 store 中定义 getters 属性。
Pinia 产生的 Store 如何解构赋值数据保持响应式? 使用 storeToRefs() 对 Store 数据进行解构,可保持响应式结构。
| 特性 | Vuex | Pinia |
|---|---|---|
| API 复杂度 | 高 | 低 |
| mutation | 必须 | 无 |
| 模块化 | 需配置 modules | 天然独立 |
| 组合式 API 支持 | 弱 | 完美支持 |
| TypeScript 支持 | 一般 | 优秀 |
| 调试体验 | 一般 | 友好 |
| 体积 | 较大 | 轻量 |