Actions and Axios in Vuex

One of the five core concepts of Vuex action,can operate arbitrary asynchronous operations, similar to mutationsbut instead mutationsof doing asynchronous operations.

Asynchronous actions are actually similar to mutations. The difference is that mutations are synchronous operations and can directly modify the state, while actions support asynchronous operations, but cannot directly modify the state, so actions submit mutations.


Here follows the previous article , simulate a piece of JSON data through php, and use the actions in the data warehouse to get the data

1. First delete the goods in the state in the page into an empty array, and then simulate and generate a JSON data in php

<?php

//目的:防止页面出现乱码,让数据中的文字正常显示
header('content-type:text/html;charset=utf-8');

$data = array(
    array('id'=>1,'name'=>'戴尔笔记本','money'=>1,'num'=>10,'jiage'=>0),
    array('id'=>2,'name'=>'惠普打印机','money'=>1,'num'=>20,'jiage'=>0),
    array('id'=>3,'name'=>'戴尔台式电脑','money'=>1,'num'=>100,'jiage'=>0)
);


// 转换为JSON格式
echo json_encode($data);

?>

2. Define a method in mutations in Vuex to get data

sendData(state,param){
                    console.log('仓库中mutations中sendData方法获取到的参数是:')
                    console.log(param.goods)
                    state.goods = param.goods;
                    console.log('--------下面是state中的goods中的内容:-----------')
                    console.log(state.goods)
             
                 }

3. Use async in actions in Vuex and call the sendData method

Define the loadingGoods method in actions, use axios to send an asynchronous request in this method, and call the server data

The method written in actions has two functions: 1. Dealing with the server 2. Dealing with mutations

 // 1.在仓库中的actions里写方法
            actions:{
                loadingGoods(store){
                    // 使用axios发送异步请求
                    axios.get('./goods.php')
                         .then((response)=>{
                            // console.log(response)
                            store.commit('sendData',{goods:response.data})
                         })
                         .catch((error)=>{
                             console.log(error)
                         })
                }
            }

4. Execute this method in the lifecycle function of the root component

  // 生命周期钩子函数
            // 2.在根组件的生命周期钩子函数中调用执行这个方法
            mounted(){
                this.$store.dispatch('loadingGoods')
//* dispatch:含有异步操作,例如向后台提交数据,写法this.$store.dispatch('action方法名',值)

            },

Guess you like

Origin blog.csdn.net/lolhuxiaotian/article/details/122099691