返回
Vuex 五大属性及其使用说明
前端
2023-12-31 02:13:02
1. State
state 是 Vuex 的核心属性,它存储着应用程序的数据。state 是一个对象,可以包含任意类型的数据,包括原始值、数组和对象。
示例
const state = {
count: 0,
todos: [],
user: null
}
2. Mutations
mutations 是 Vuex 中用于修改 state 的唯一方法。mutations 是函数,它们接收 state 作为第一个参数,并可以修改 state 的值。
示例
const mutations = {
increment(state) {
state.count++
},
addTodo(state, todo) {
state.todos.push(todo)
},
setUser(state, user) {
state.user = user
}
}
3. Getters
getters 是用于从 state 中获取数据的函数。getters 是函数,它们接收 state 作为第一个参数,并返回一个值。
示例
const getters = {
getTodosByStatus: (state) => (status) => {
return state.todos.filter(todo => todo.status === status)
},
getCompletedTodosCount: (state) => {
return state.todos.filter(todo => todo.completed).length
},
getUserFullName: (state) => {
return state.user ? `${state.user.firstName} ${state.user.lastName}` : ''
}
}
4. Actions
actions 是用于执行异步操作的函数。actions 是函数,它们接收 context 作为第一个参数,context 是一个对象,它包含 state、getters 和 commit 函数。
示例
const actions = {
fetchTodos({ commit }) {
fetch('https://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then(todos => {
commit('setTodos', todos)
})
},
createUser({ commit }, data) {
fetch('https://example.com/api/users', {
method: 'POST',
body: JSON.stringify(data)
})
.then(res => res.json())
.then(user => {
commit('setUser', user)
})
}
}
5. Modules
modules 是用于将 Vuex store 拆分成多个模块的功能。每个模块都有自己的 state、mutations、getters 和 actions。
示例
const modules = {
todos: {
state: {
todos: []
},
mutations: {
addTodo(state, todo) {
state.todos.push(todo)
}
},
getters: {
getTodosByStatus: (state) => (status) => {
return state.todos.filter(todo => todo.status === status)
}
},
actions: {
fetchTodos({ commit }) {
fetch('https://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then(todos => {
commit('setTodos', todos)
})
}
}
},
users: {
state: {
user: null
},
mutations: {
setUser(state, user) {
state.user = user
}
},
getters: {
getUserFullName: (state) => {
return state.user ? `${state.user.firstName} ${state.user.lastName}` : ''
}
},
actions: {
createUser({ commit }, data) {
fetch('https://example.com/api/users', {
method: 'POST',
body: JSON.stringify(data)
})
.then(res => res.json())
.then(user => {
commit('setUser', user)
})
}
}
}
}
总结
Vuex 是一个强大的状态管理库,可以帮助您管理大型项目的公共数据。本文介绍了 Vuex 的五个属性:state、mutations、getters、actions 和 modules,并演示了如何使用它们来管理数据。希望本文能对您有所帮助。
扩展阅读

扫码关注微信公众号
构建更优化的代码:告别if/else嵌套,畅游遍历世界

React轻松接入高德地图,GeoHash值一键转换,轻松实现区域自动填充!

你一定不知道的 JS 操作符,简直绝了!
用Canvas做吉利画笔,添彩用户体验
