vue2使用vuex示例

这篇博客介绍了如何在Vue2项目中使用Vuex3,包括安装vuex@3.4.0,将Vuex引入到main.js,并在src根目录下创建store文件夹及index.js文件,提供了一个简单的使用示例。

前言

vue2 对应vuex 3版本,别下错了。

安装

npm i vuex@3.4.0

在main.js中

import store from './store'

new Vue({
  router,
  store,	// 将store挂载到app上
  render: h => h(App)
}).$mount('#app')

新建store文件

在src根目录下新建store文件夹,新建index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 创建一个新的 store 实例, 并默认导出
export default new Vuex.Store({
    state: {
        count: 1,
        info: 'state.info',
        todos: [
            { id: 1, text: '...', done: true },
            { id: 2, text: '...', done: false }
        ]
    },
    getters: {  // 相当于 计算属性
        getInfo: state => {
            return '这是get获取来的数据:' + state.info;
        },
        getTodos: state => {
            return state.todos.filter(todo => todo.done);
        }
        
    },
    mutations: {    // 同步的
        addCount(state) {
            state.count++;
        },
        minCount(state) {
            state.count--;
        },
        amountCount(state, payload) {
            state.count = payload.num
        },
        asyncAddCount(state) {
            state.count++;
        }
    },
    actions: {      // 跟mutations相似,可以异步的
        asyncCount(content) {
            setTimeout(() => {
                content.commit('asyncAddCount');
            }, 2000);
        }
    }
})

使用示例

<template>
  <div>
    Vuex 页面:
    
    <!-- state 使用方法 -->
    <div>{{ count }}</div>

    <!-- mutations 使用方法 -->
    <button @click="add">点击加加</button>
    <button @click="min">点击减减</button>
    <button @click="amount({num: 10})">等于10</button>

    <!-- getter 使用方法 -->
    <div>{{ getInfo }}</div>
    <div>{{ getTodos }}</div>

    <!-- actions 使用方法 -->
    <button @click="asyncHandler">异步执行</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  computed: {
    ...mapState(['count']), // 通过辅助函数获取 state 数据
    ...mapGetters(['getInfo', 'getTodos']) // getter使用方法
  },
  methods: {
    // 提交告诉给 addCount 方法
    // mapMutations 使用方式一
    add() {
      this.$store.commit('addCount')
    },

    // mapMutations 使用方式二
    ...mapMutations({
      min: 'minCount'
    }),

    // 载荷传参 - 方式一:第二个参数
    // amount() {
    //   this.$store.commit({
    //     type: 'amountCount',
    //     num: 10
    //   })
    // },
    // 载荷传参 - 方式二: 对象type方式
    // amount() {
    //   this.$store.commit({
    //     type: 'amountCount',
    //     num: 10
    //   })
    // },
    // 载荷传参 - 方式三 该方式 amount方法会自动传参(在映射该方法时,传参过来,见模板的amount)
    ...mapMutations({
      amount: 'amountCount'
    }),

    // actions 方式一
    asyncHandler() {
      this.$store.dispatch('asyncCount')
      console.log('前面有异步,所以这行先执行');
    },
    // actions 方式二
    // ...mapActions({
    //   asyncHandler: 'asyncCount'
    // })

  }
}
</script>

<think>我们正在使用Vue2Vuex。在Vuex中,getters用于从store中派生出一些状态,例如对列表进行过滤或计数等。 下面是一个简单的Vuex store示例,展示如何定义getters,并在Vue组件中引用它们。 步骤: 1. 定义Vuex store,包括state和getters。 2.Vue组件中通过`this.$store.getters`访问getters,或者使用mapGetters辅助函数。 示例代码: 首先,定义一个store: ```javascript import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '学习Vue', done: true }, { id: 2, text: '学习Vuex', done: false }, { id: 3, text: '学习Getter', done: false } ] }, getters: { // 返回所有未完成的todos undoneTodos: state => { return state.todos.filter(todo => !todo.done); }, // 返回未完成todos的数量 undoneTodosCount: (state, getters) => { return getters.undoneTodos.length; }, // 通过id获取todo getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id); } } }); ``` 在Vue组件中,我们可以这样使用: 方法1:直接通过`this.$store.getters`访问 ```vue <template> <div> <h2>未完成的任务</h2> <ul> <li v-for="todo in undoneTodos" :key="todo.id">{{ todo.text }}</li> </ul> <p>未完成任务数量: {{ undoneTodosCount }}</p> <p>ID为1的任务: {{ getTodoById(1).text }}</p> </div> </template> <script> export default { computed: { undoneTodos() { return this.$store.getters.undoneTodos; }, undoneTodosCount() { return this.$store.getters.undoneTodosCount; }, getTodoById() { return this.$store.getters.getTodoById; } } } </script> ``` 方法2使用`mapGetters`辅助函数,简化代码 ```vue <template> <!-- 同上 --> </template> <script> import { mapGetters } from 'vuex'; export default { computed: { // 使用对象展开运算符将getter混入computed对象中 ...mapGetters([ 'undoneTodos', 'undoneTodosCount', 'getTodoById' ]) // 如果你想将一个getter属性另取一个名字,使用对象形式: // ...mapGetters({ // todos: 'undoneTodos', // count: 'undoneTodosCount', // getTodo: 'getTodoById' // }) } } </script> ``` 注意: - getters可以依赖其他getters,如上面示例中的`undoneTodosCount`依赖于`undoneTodos`。 - 如果getter需要传递参数,则需要使用方法形式(返回一个函数),如上面的`getTodoById`。 §§相关问题§§ 1. Vuex中getters和computed属性有什么异同? 2. 如何在Vuex的getters中传递动态参数? 3. 使用mapGetters辅助函数时有哪些注意事项? 4. Vuex的getters能否进行异步操作?为什么? 5. 如何测试Vuex中的getters? </think>### Vue2Vuex Getters 的使用及引用示例Vue2使用 Vuex 的 **`getters`** 可以方便地从 store 中派生出计算状态(类似组件的计算属性)。以下是具体用法和示例: --- #### 1. **定义 Getters** 在 Vuex Store 中声明 `getters`(通常与 `state` 搭配): ```javascript // store/index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { products: [ { id: 1, name: "手机", price: 3000, stock: 10 }, { id: 2, name: "电脑", price: 8000, stock: 5 } ] }, getters: { // 获取所有商品 allProducts: state => state.products, // 根据最低价格过滤商品 cheapProducts: state => minPrice => { return state.products.filter(item => item.price >= minPrice); }, // 计算库存总量 totalStock: (state, getters) => { return getters.allProducts.reduce((sum, item) => sum + item.stock, 0); } } }); ``` #### 2. **在组件中引用 Getters** ##### 方法一:直接通过 `$store.getters` 访问 ```vue <template> <div> <p>库存总量: {{ totalStock }}</p> <ul> <li v-for="item in cheapProducts(5000)" :key="item.id"> {{ item.name }} - ¥{{ item.price }} </li> </ul> </div> </template> <script> export default { computed: { totalStock() { return this.$store.getters.totalStock; }, cheapProducts() { return this.$store.getters.cheapProducts; // 返回函数,可传参数 } } }; </script> ``` ##### 方法二:使用 `mapGetters` 辅助函数(推荐) ```vue <template> <!-- 同上 --> </template> <script> import { mapGetters } from 'vuex'; export default { computed: { // 映射为计算属性 ...mapGetters([ 'totalStock', // 直接映射为 this.totalStock 'cheapProducts' // 映射为 this.cheapProducts(minPrice) ]), // 重命名(可选) ...mapGetters({ productList: 'allProducts' // 映射为 this.productList }) } }; </script> ``` --- #### 关键特性说明 1. **依赖响应性**: - 当 `state.products` 变化时,`getters` 自动更新。 2. **传递参数**: - 通过返回函数实现(如 `cheapProducts`),调用时传入参数:`cheapProducts(5000)`。 3. **组合其他 Getter**: - 在 `totalStock` 中通过 `getters` 参数调用 `allProducts`,避免冗余逻辑。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值