使用 Vuex + axios 发送请求

Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource

目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求,而大型项目都会使用 Vuex 来管理数据,所以这篇博客将结合两者来发送请求

 

前言: 

Vuex 的安装将不再赘述,可以参考之前的博客 Vue 爬坑之路(四)—— 与 Vuex 的第一次接触

使用 cnpm 安装 axios

cnpm install axios -S

安装其他插件的时候,可以直接在 main.js 中引入并 Vue.use(),但是 axios 并不能 use,只能每个需要发送请求的组件中即时引入

为了解决这个问题,有两种开发思路,一是在引入 axios 之后,修改原型链,二是结合 Vuex,封装一个 aciton。具体的实施请往下看~

 

方案一:改写原型链

首先在 main.js 中引入 axios

import axios from 'axios'

这时候如果在其它的组件中,是无法使用 axios 命令的。但如果将 axios 改写为 Vue 的原型属性,就能解决这个问题

Vue.prototype.$ajax = axios

在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $ajax 命令

复制代码
methods: {
  submitForm () {
    this.$ajax({
      method: 'post',
      url: '/user',
      data: {
        name: 'wise',
        info: 'wrong'
      }
   })
}
复制代码

 

 

方案二:在 Vuex 中封装

之前的文章中用到过 Vuex 的 mutations,从结果上看,mutations 类似于事件,用于提交 Vuex 中的状态 state

action 和 mutations 也很类似,主要的区别在于,action 可以包含异步操作,而且可以通过 action 来提交 mutations

另外还有一个重要的区别:

mutations 有一个固有参数 state,接收的是 Vuex 中的 state 对象

action 也有一个固有参数 context,但是 context 是 state 的父级,包含  state、getters

 

Vuex 的仓库是 store.js,将 axios 引入,并在 action 添加新的方法

复制代码
// store.js
import Vue from 'Vue' import Vuex from 'vuex' // 引入 axios import axios from 'axios' Vue.use(Vuex) const store = new Vuex.Store({ // 定义状态 state: { test01: { name: 'Wise Wrong' }, test02: { tell: '12312345678' } }, actions: { // 封装一个 ajax 方法 saveForm (context) { axios({ method: 'post', url: '/user', data: context.state.test02 }) } } }) export default store
复制代码

注意:即使已经在 main.js 中引入了 axios,并改写了原型链,也无法在 store.js 中直接使用 $ajax 命令

换言之,这两种方案是相互独立的

 

在组件中发送请求的时候,需要使用 this.$store.dispatch 来分发

methods: {
  submitForm () {
    this.$store.dispatch('saveForm')
  }
}

submitForm 是绑定在组件上的一个方法,将触发 saveForm,从而通过 axios 向服务器发送请求

 

 

附录:配置 axios 

上面封装的方法中,使用了 axios 的三个配置项,实际上只有 url 是必须的,完整的 api 可以参考使用说明

为了方便,axios 还为每种方法起了别名,比如上面的 saveForm 方法等价于:

axios.post('/user', context.state.test02)

完整的请求还应当包括 .then 和 .catch

.then(function(res){
  console.log(res)
})
.catch(function(err){
  console.log(err)
})

当请求成功时,会执行 .then,否则执行 .catch

这两个回调函数都有各自独立的作用域,如果直接在里面访问 this,无法访问到 Vue 实例

这时只要添加一个 .bind(this) 就能解决这个问题

.then(function(res){
  console.log(this.data)
}.bind(this))
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我来简单介绍一下使用 Vue 组件、Vue 路由、VuexAxios 实现增删改查的步骤。 1. 安装必要的依赖: ``` npm install vue vue-router vuex axios --save ``` 2. 创建 Vue 组件: 在 src/components 目录下创建四个组件,分别是 List、Add、Edit 和 Detail。这四个组件分别用于展示列表、新增数据、编辑数据和查看详情。 List.vue 组件: ``` <template> <div> <h3>数据列表</h3> <table> <thead> <tr> <th>ID</th> <th>名称</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="item in list" :key="item.id"> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td> <router-link :to="{ name: 'detail', params: { id: item.id }}">查看</router-link> <router-link :to="{ name: 'edit', params: { id: item.id }}">编辑</router-link> <button @click="handleDelete(item.id)">删除</button> </td> </tr> </tbody> </table> <router-link :to="{ name: 'add' }">新增</router-link> </div> </template> <script> export default { data() { return { list: [] } }, methods: { handleDelete(id) { // 发送删除请求 this.$axios.delete(`/api/data/${id}`).then(() => { // 删除成功后重新获取数据 this.getList() }) }, getList() { // 发送获取列表请求 this.$axios.get('/api/data').then(res => { this.list = res.data }) } }, created() { // 页面创建时获取数据列表 this.getList() } } </script> ``` Add.vue 组件: ``` <template> <div> <h3>新增数据</h3> <form @submit.prevent="handleSubmit"> <label> 名称: <input type="text" v-model="formData.name" /> </label> <button type="submit">提交</button> </form> </div> </template> <script> export default { data() { return { formData: { name: '' } } }, methods: { handleSubmit() { // 发送新增请求 this.$axios.post('/api/data', this.formData).then(() => { // 新增成功后跳转到列表页 this.$router.push({ name: 'list' }) }) } } } </script> ``` Edit.vue 组件: ``` <template> <div> <h3>编辑数据</h3> <form @submit.prevent="handleSubmit"> <label> 名称: <input type="text" v-model="formData.name" /> </label> <button type="submit">提交</button> </form> </div> </template> <script> export default { data() { return { formData: { name: '' } } }, methods: { handleSubmit() { // 发送编辑请求 this.$axios.put(`/api/data/${this.$route.params.id}`, this.formData).then(() => { // 编辑成功后跳转到列表页 this.$router.push({ name: 'list' }) }) }, getData() { // 发送获取数据请求 this.$axios.get(`/api/data/${this.$route.params.id}`).then(res => { this.formData = res.data }) } }, created() { // 页面创建时获取数据 this.getData() } } </script> ``` Detail.vue 组件: ``` <template> <div> <h3>数据详情</h3> <p>ID:{{ data.id }}</p> <p>名称:{{ data.name }}</p> <button @click="$router.push({ name: 'list' })">返回</button> </div> </template> <script> export default { data() { return { data: {} } }, methods: { getData() { // 发送获取数据请求 this.$axios.get(`/api/data/${this.$route.params.id}`).then(res => { this.data = res.data }) } }, created() { // 页面创建时获取数据 this.getData() } } </script> ``` 3. 创建 Vue 路由: 在 src/router/index.js 文件中定义四个路由,分别对应 List、Add、Edit 和 Detail 组件。 ``` import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/list' }, { path: '/list', name: 'list', component: () => import('../components/List.vue') }, { path: '/add', name: 'add', component: () => import('../components/Add.vue') }, { path: '/edit/:id', name: 'edit', component: () => import('../components/Edit.vue') }, { path: '/detail/:id', name: 'detail', component: () => import('../components/Detail.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router ``` 4. 创建 Vuex store: 在 src/store/index.js 文件中创建一个 Vuex store,用于管理全局状态。 ``` import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: { increment(context) { context.commit('increment') } }, modules: {} }) ``` 5. 在 main.js 中配置 Axios: 在 main.js 中配置 Axios,使其可以全局使用。 ``` import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import axios from 'axios' Vue.config.productionTip = false Vue.prototype.$axios = axios new Vue({ router, store, render: h => h(App) }).$mount('#app') ``` 6. 在 App.vue 中使用组件: 在 App.vue 中引入 List 组件,并在模板中使用 router-view 标签来渲染路由组件。 ``` <template> <div id="app"> <router-view></router-view> </div> </template> <script> import List from './components/List.vue' export default { components: { List } } </script> ``` 7. 启动应用: 在命令行中执行以下命令启动应用: ``` npm run serve ``` 至此,一个简单的使用 Vue 组件、Vue 路由、VuexAxios 实现增删改查的应用就完成了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值