Vue3 创建实例

使用 setup

1
2
3
4
5
6
7
const { createApp } = Vue
createApp({
setup() {
// ...
}
})
.mount('#app') // 挂载到 #app

使用 Options API

1
2
3
4
5
6
7
8
9
const { createApp } = Vue
createApp({
data() {
return {}
},
methods: {},
// ...
})
.mount('#app') // 挂载到 #app

Pinia 定义 Store

defineStore 的第一个参数是 store 的 id,必须是唯一的。第二个参数是一个选项对象。

使用 Setup Store

1
2
3
4
5
6
7
8
9
10
const { ref } = Vue
const { defineStore } = Pinia
const useTestStore = defineStore('test', () => {
const count = ref(1)
const doubleCount = computed(() => count.value * 2)
const increment = () => {
count.value++
}
return { count, doubleCount, increment }
})

使用 Option Store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const { defineStore } = Pinia
const useTestStore = defineStore('test', {
// 状态数据
state: () => ({
count: 1
}),
// 计算属性
getters: {
doubleCount: (state) => state.count * 2
},
// 方法
actions: {
increment() {
this.count++
}
}
})

Vue3 使用 Pinia

1
2
3
4
5
6
7
8
9
10
11
const { createApp, ref } = Vue
const { createPinia } = Pinia
// 定义 Store
const useTestStore = defineStore('test', () => {
const count = ref(1)
const doubleCount = computed(() => count.value * 2)
const increment = () => {
count.value++
}
return { count, doubleCount, increment }
})
1
2
3
4
5
6
7
8
9
10
11
// Options API
createApp({
data() {
return {
testStore: useTestStore()
}
}
})
// 使用 Pinia
.use(createPinia())
.mount('#app')
1
2
3
4
5
6
7
8
9
10
// Setup
createApp({
setup(){
const testStore = useTestStore()
return { testStore }
}
})
// 使用 Pinia
.use(createPinia())
.mount('#app')
1
2
3
4
5
6
<!-- 显示 -->
<div id="app">
{{ testStore.count }}
{{ testStore.doubleCount }}
<button @click="testStore.increment">按钮</button>
</div>