• vuex 中的 action


     action 在 vuex 中用于异步 commit 的发送 

    store.js

    import Vue from "vue";
    import Vuex from "vuex";
     
    
    Vue.use(Vuex);
    const store = new Vuex.Store({
        //这里的state必须是JSON,是一个对象。
        state: {
            count: 0 ,        //这里就是初始值的罗列,
            student : [
                {"name" : "小1" , "sex" : "男" },
                {"name" : "小2" , "sex" : "女" },
                {"name" : "小3" , "sex" : "男" },
                {"name" : "小4" , "sex" : "女" }
            ]
        },
        //突变,罗列所有可能改变state的方法
        mutations: {
            //没有所谓的大写字母的Type了,就是一个一个函数
            add (state  , n ) {
                  state.count += n;
            },
            minus (state) {
                state.count--;
            }
        },
        actions : {
            add(context,payload){
                $.get("api.txt",function(data){
                    context.commit('add',Number(data));
                });
            }
        }, 
      //另一种写法
    //*  actions: {
    //*    add ({commit},args) {
    //*    $.get("api.txt",function(data){
    //*       
    commit('add',Number(data));
    //*    });
    //* }

    getters : { nansheng : state
    => { return state.student.filter((item)=>{ return item.sex == "男"; }) } } }); export default store;

    .vue文件

    <style scopoed>
     
    </style>
    
    <template>
        <div>
            我是子组件
            <h1>
                <button v-on:click="minusnandler">减少</button>
                {{count}}
                <button v-on:click="addhandler">增加</button>
            </h1>
            <h1>
                {{nansheng}}
            </h1>
        </div>
    </template>
    
    <script>
        export default {
            data(){
                return {
                    m : 6,
                    n : 0
                }
            },
            computed : {
                count(){
                    return this.$store.state.count;
                },
                nansheng (){
                    return this.$store.getters.nansheng
                }
            },
            methods : {
                addhandler(){
                    this.$store.dispatch("add");  //添加的数字写在文本文件中了,是异步读取的,所以不能直接commit
                },
                minusnandler(){
                    this.$store.commit("minus");
                }
            }
        }
    </script>
  • 相关阅读:
    谈谈图片上传及canvas压缩的流程
    前端应该懂得初级Web分析指标
    java OPENCV 连通域, Imgproc.findContours 例子,参数说明
    [学习opencv]高斯、中值、均值、双边滤波
    Opencv 图像叠加 添加水印
    帧间提取水印
    opencv mat 转灰度图
    编写一条sql命令,sql删除没有中文的表
    使用JavaCV/OpenCV抓取并存储摄像头图像
    周掌柜
  • 原文地址:https://www.cnblogs.com/caoleyun/p/12693173.html
Copyright © 2020-2023  润新知