首页 > 解决方案 > 如何使用 Vue 在 Vue 中创建通用函数?

问题描述

我想制作一个通用函数来使用内部突变和方法。该函数接收一个参数,然后返回一个布尔值,例如:

estadoFunction(date){
            var dateObj = new Date();
            var month = dateObj.getUTCMonth() + 1; //months from 1-12
            var day = dateObj.getUTCDate();
            var year = dateObj.getUTCFullYear();
            var fechaActual = new Date(year + "-" + month + "-" + day);
            var fechaInicioEvento = new Date(date);
            if(fechaInicioEvento > fechaActual){
                return true;
            }else{
                return false;
            }
        }

我想在方法和突变中使用estadoFunction(date),例如:

methods: {
        estado(date){
            if(this.estadoFunction(date)){
                return "Abierto";
            }else{
                return "Cerrado";
            }
        }
    }

我尝试创建一个突变,然后在另一个带有提交的突变中使用它,但estadoFunction(date)返回未定义,另一方面console.log("true")console.log("false")正在工作。

mutations: {
        llamarJsonMutation(state, llamarJsonAction){

            state.programas = llamarJsonAction.BD_programas;

            //filtro por eventos cerrados y abiertos
            llamarJsonAction.Nueva_estructura_proveedor.forEach( item => {
                if(this.commit("estadoFunction", item.fechaFin)){
                    state.actividadesPrimerFiltro.push(item);
                }
            });

            state.actividades = state.actividadesPrimerFiltro.sort((a, b) => parseFloat(a.fechaInicio) - parseFloat(b.fechaInicio));
        },
        estadoFunction(date){
            var dateObj = new Date();
            var month = dateObj.getUTCMonth() + 1; //months from 1-12
            var day = dateObj.getUTCDate();
            var year = dateObj.getUTCFullYear();
            var fechaActual = new Date(year + "-" + month + "-" + day);
            var fechaInicioEvento = new Date(date);
            if(fechaInicioEvento > fechaActual){
                console.log("true");
                return true;
            }else{
               console.log("false");
                return false;
            }
        }
    }

你能帮我吗?这是我完整的javascript代码:

//componentes
Vue.component('actividades', {
    template: /*html*/
        ` 
        <div class="col-lg-8">
            <template v-for="(item, key) in actividades">
                <ul>
                    <li>{{ estado(item.fechaFin) }}</li>
                <ul>
            </template>
        </div>
        `,
    computed: {
        ...Vuex.mapState(['actividades','programas']),
    },
    methods: {
        estado(date){
            if(this.estadoFunction(date)){
                return "Abierto";
            }else{
                return "Cerrado";
            }
        }
    }
});

//VueEx
const store = new Vuex.Store({
    state: {
        actividadesPrimerFiltro: [],
        actividades: [],
        programas: []
    },
    mutations: {
        llamarJsonMutation(state, llamarJsonAction){

            state.programas = llamarJsonAction.BD_programas;

            //filtro por eventos cerrados y abiertos
            llamarJsonAction.Nueva_estructura_proveedor.forEach( item => {
                if(this.commit("estadoFunction", item.fechaFin)){
                    state.actividadesPrimerFiltro.push(item);
                }
            });

            state.actividades = state.actividadesPrimerFiltro.sort((a, b) => parseFloat(a.fechaInicio) - parseFloat(b.fechaInicio));
        },
        estadoFunction(date){
            var dateObj = new Date();
            var month = dateObj.getUTCMonth() + 1; //months from 1-12
            var day = dateObj.getUTCDate();
            var year = dateObj.getUTCFullYear();
            var fechaActual = new Date(year + "-" + month + "-" + day);
            var fechaInicioEvento = new Date(date);
            if(fechaInicioEvento > fechaActual){
                return true;
            }else{
                return false;
            }
        }
    },
    actions: {
        llamarJson: async function({ commit }){
            const data = await fetch('calendario-2021-prueba.json');
            const dataJson = await data.json();
            commit('llamarJsonMutation', dataJson);
        }
    }
});

//Vue
new Vue({
    el: '#caja-vue',
    store: store,
    created(){
        this.$store.dispatch('llamarJson');
    }
});

标签: javascriptvue.jsvuejs2vue-componentvuex

解决方案


突变不应该调用其他突变(动作可以调用多个突变)并且您不应该对突变/动作的返回值感兴趣。

如果您使用的是 Vue CLI 之类的打包工具,最好为它创建一个单独的模块(例如Utilities.js)并将其导入到商店和任何组件中。

由于您使用的是 CDN,因此您可以estadoFunction在 Vue 代码上方定义。例如:

estadoFunction(date){
...
}

/***** App begins here *****/
//componentes
Vue.component('actividades', {
...
}

并直接在任何地方使用它。例如,在您的estado方法中:

methods: {
  estado(date){
    if(estadoFunction(date)){
        return "Abierto";
    }else{
        return "Cerrado";
    }
  }
}

推荐阅读