Vue3 创建实例
使用 setup
1 2 3 4 5 6 7
| const { createApp } = Vue createApp({ setup() { } }) .mount('#app')
|
使用 Options API
1 2 3 4 5 6 7 8 9
| const { createApp } = Vue createApp({ data() { return {} }, methods: {}, }) .mount('#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
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
| createApp({ data() { return { testStore: useTestStore() } } })
.use(createPinia()) .mount('#app')
|
1 2 3 4 5 6 7 8 9 10
| createApp({ setup(){ const testStore = useTestStore() return { testStore } } })
.use(createPinia()) .mount('#app')
|
1 2 3 4 5 6
| <div id="app"> {{ testStore.count }} {{ testStore.doubleCount }} <button @click="testStore.increment">按钮</button> </div>
|