【笔记】vuex

149 阅读1分钟

axios

使用基于 promise 的 HTTP 客户端 axios 完成 ajax 请求

安装

npm install axios

使用

  • vue 页面上
import axios from axios

Vue.prototype.$http = axios
  • 使用方法

  • get 请求

axios.get().then(response).catch(error)
  • post 请求
axios.post().then(response).catch(error)

vuex

是一个专为 Vue.js 应用程序开发的状态管理模式,采用集中式存储管理应用的所有组件状态

核心是 store。

vuex 优缺点

  • 优点

    • 适用于大型单页面应用
    • 解决非父子组件的信息传递(将数据存放在 state)
    • 减少了 Ajax 请求,有些可以从 state 中直接调用
  • 缺点

    • 刷新浏览器,state 会变为初始状态

vuex 和全局对象的对比

  • vuex 的状态存储是响应式的
  • 不能直接更改 store 中的状态

store

  • store.state 获取状态对象
  • store.commit 触发状态变更 mutation

属性

state

用来存储数据的容器

mutation

更改 store 状态的唯一方法,是提交更新数据的方法

mutation 必须是同步函数

mutations: {
increase(state){
state.count++
}
}

store.commit('increase')
------------------------
mutations: {
increase(state.playload){
state.count += playload.amount
}
}

store.commit('increase',{
amount: 10
})

在组件中提交 mutation

this.$store.commint('increase')

action

Action 提交的是 mutation,不是直接变更状态。

Action 可以包含任意异步操作。

mutations: {
increase(state){
state.count++
}
},
actions: {
increaseAction(context){
context.commit('increase')
}
}
actions分发,可以在actions内进行异步操作
```js
store,dispatch('increase')

getter

可以认为是 store 的计算属性