在vue3中使用vue2中的写法也可以 但是这里我们使用组合api来使用vuex的数据和各种方法
- 打开store中的index.js 代码如下
-
// 可以看出与vue2的写法有些区别,但是用法一样 // 但是需要注意的是如果在创建项目时没有安装vuex 则需要自己安装 安装命令是 npm install vuex@next --save 这里需要注意命令的不同 安装的版本就不同 import { createStore } from 'vuex' export default createStore({ state: { // 用来写要存储的状态(数据) name: '张三', age: 16 }, getters: { // 相当于vue中的计算属性 changeAge(state) { return state.age + '岁' } }, mutations: { // 修改state数据的唯一方法就是提交mutation changeName(state, value) { state.name = value }, changeProducts(state, value=[]) { state.products = value } }, actions: { // 异步处理数据的方法 通过提交mutation修改数据 不建议直接修改 这里直接修改也可以 但是当前情况下框架不完善 所以不建议直接修改 getProducts({commit}) { setTimeout(() => { commit('changeProducts', [{name: '这是一个商品'}]) }, 1000) } }, modules: { // 模块化方法 }, plugins: [] // 插件使用的位置 })
下面是使用过程
<template>
<div class="home">
{{name}} - {{age}}
<button @click="changeName('李四')">修改名字</button>
<button @click="getProducts">点击获取商品数据</button>
<ul>
<li v-for="(item, i) in products" :key="i">{{item.name}}</li>
</ul>
</div>
</template>
<script>
// defineComponent 定义一个组件的方法 返回值是传递给函数的对象 也可以接收一个函数作为参数
// 函数的名将可以作为组件的名字使用 该方法用在ts代码中会更有用,因为ts中可以注明配置项的参数类型
// 在js中使用意义不是很大, 但是我们这里尽量尊重vue3
// computed 计算属性 返回一个ref类型的数据 ref是vue3用来声明具有相应式的基本数据类型的方法
import { defineComponent, computed } from 'vue'
// useStore 可以将store中的数据和方法获取到的方法
import { useStore } from 'vuex';
export default defineComponent({
// vue3的组合api 运行在beforeCreate之前 为了方式this使用错误 setup中直接将this的值设置成了undefined 所以在setup中没有this
setup() {
let store = useStore()
// console.log(store.state);
// 在setup中定义的方法和数据如果需要在页面中使用 则需要先将数据或者方法返回
return {
name: computed(() => store.state.name),
age: computed(() => store.getters.changeAge),
changeName: (name) => store.commit('changeName', name), // 使用mutation方法的函数
getProducts: () => store.dispatch('getProducts'), // 调用actions函数的方法
products: computed(() => store.state.products)
}
}
})
</script>