• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Yancy00

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

vuex插件使用

vuex是什么?

vuex是vue官方提供的一个插件,集中式管理项目中共用的数据
安装: vue2只能用vuex的3版本: npm install vuex@3

vuex组成部分:

  • actions
  • mutations
  • modules
  • state
  • getters
vuex基本使用

创建 ./src/store/index.js文件

store/index.js内容如下:
import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex)
let timer
const actions = { //书写业务逻辑,处理异步请求
    add(ctx) {
        clearTimeout(timer)
        timer = setTimeout(() => {
            ctx.commit('ADD')
        }, 1000)
    }
}
const mutations = {
    ADD(state) {
        state.count++
    },
    SUB(state) {
        state.count--
    }

} //修改state中数据
const state = { // vuex仓库存储数据的地方
    count: 1
}
const getters = {} // 简化包装组件获取仓库数据,类似computed

export default new Vuex.Store({
    actions, mutations, state, getters
})
main.js文件:
import Vue from 'vue'
import App from './App.vue'
import store from "@/store/index"

new Vue({
    render: h => h(App),
    store//组件实例身上会多个属性 $store
}).$mount("#app")
app.vue文件:
<template>
  <div id="app">
    <button @click="add">加1</button>
    仓库数据: count={{ count }}
    <button @click="sub">减1</button>

  </div>
</template>

<script>
import {mapState} from "vuex";

export default {
  name: 'App',
  computed: {
    ...mapState(['count'])
  },
  methods: {
    add() {
      this.$store.dispatch('add')
    },
    sub() {
      this.$store.commit('SUB', 1)
    }
  }
}
</script>
vuex工具使用

vuex的工具整合在vue工具里,不用额外安装
image

vuex模块化

项目功能很多时,把大仓库拆分为很多个小仓库分别存储每个功能模块的数据操作
在./src/store目录下按功能创建, home/index.js, search/index.js里面分别写各个模块的数据操作,最后整合到./src/store/inde.js文件中.

./src/store/home/index.js
// home模块的仓库
const state = {
    a:1
}
const actions = {}
const mutations = {}
const getters = {}

export default {state, actions, mutations, getters}
./src/store/search/index.js
// search模块的仓库
const state = {
    user: {
        age: 18,
        name: '张三'
    }
}
const actions = {}
const mutations = {}
const getters = {}

export default {state, actions, mutations, getters}
./src/store/index.js
import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex)

import home from "@/store/home";
import search from "@/store/search";


export default new Vuex.Store({
    modules: {
        home, search
    }
})

posted on 2023-09-13 16:05  Yancy00  阅读(66)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3