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工具里,不用额外安装
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
}
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?