繁体   English   中英

如何在模板内使用返回值的 function? Vuex, Vue

[英]How to use function that return value inside a template? Vuex, Vue

我正在使用模板获取 json 文件的数据,我使用“v-for”打印所有数据,例如:

template: /*html*/
    ` 
    <div class="col-lg-8">
        <template v-for="item of actividades">
            <ul>
                <li>{{ item.date }}</li>
            <ul>
        </template>
    </div>
    `,

但我需要使用函数 year() 来修改这些信息并返回和结果,例如:

   template: /*html*/
    ` 
    <div class="col-lg-8">
        <template v-for="item of actividades">
            <ul>
                <li>{{ year(item.date) }}</li>
            <ul>
        </template>
    </div>
    `,

值 {{ item.date }} 打印“2021-01-20”,但我希望使用 function {{ year(item.date) }} 打印“2021”

代码 function year() 使用 javascript:

year(date){
            return String(date).substr(0, 4);
        }

我尝试使用该代码但无法正常工作,出现此错误:此图像显示错误

那是我的 javascript 代码:

//VueEx
const store = new Vuex.Store({
    state: {
        actividades: [],
        programas: [],
        year: ""
    },
    mutations: {
        llamarJsonMutation(state, llamarJsonAction){
            state.actividades = llamarJsonAction.Nueva_estructura_proveedor;
            state.programas = llamarJsonAction.BD_programas;
        },
        yearFunction(state, date){
            state.year = String(date).substr(8, 2);
            return state.year;
        }
    },
    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');
      }
});

在模板中,您可以使用定义为methodscomputed的函数。 从技术上讲,您也可以使用data将 function 传递给模板,但我不建议这样做。 并不是说它不起作用,但是 Vue 使data中声明的任何内容都具有响应性,并且使 function(基本上是一个常数)具有响应性是没有意义的。 所以,在你的情况下:

 new Vue({ el: '#app', data: () => ({ actividades: [ { date: '2021-01-20' }, { date: '2020-01-20' }, { date: '2019-01-20' }, { date: '2018-01-20' }, { date: '2017-01-20' } ] }), methods: { year(date) { return date.substring(0, 4); } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <ul> <li v-for="(item, key) in actividades":key="key"> {{ year(item.date) }} </li> </ul> </div>

如果由于某种原因,您想通过computedyear

computed: {
  year() { return date => date.substring(0, 4); }
}

但它是一个复杂的构造(一个 getter function 返回一个内部箭头函数),这种复杂性没有任何用途。 我建议您在您的情况下使用一种method ,因为它是最直接的(易于阅读/理解)。


如果您要从另一个文件中导入year function:

import { year } from '../helpers'; // random example, replace with your import

// inside component's methods:

methods: {
  year, // this provides `year` imported function to the template, as `year`
        // it is equivalent to `year: year,`
  // other methods here
}

旁注:

  • 遍历包含<ul><template>标记是没有意义的。 您可以将 v-for 直接放在<ul>上并丢失<template> (您应该仅在想要应用一些逻辑时使用<template> - 即: v-if - 到一堆元素而不实际包装将它们放入 DOM 包装器中;另一个用例是当您希望其子代是其父代的直接后代时:对于<ul> / <li><tbody> / <tr>关系,您不能有中介它们之间的包装器)。 在您的情况下,将v-for放在<ul>上会以更少的代码产生完全相同的结果。
  • 您应该始终key您的v-for<ul v-for="(item, key) in actividades":key="key"> Keys 帮助 Vue维护列表元素的 state ,跟踪动画并正确更新它们

我看到您正在尝试使用 Vuex 商店。 并在模板语法中使用突变。

不确定我们是否可以像您正在做的那样直接通过 HTML 调用突变。 过去,当我尝试调用突变时,我会:

 Vue.component('followers', { template: '<div>Followers: {{ computedFollowers }} {{printSampleLog()}}</div>', data() { return { followers: 0 } }, created () { this.$store.dispatch('getFollowers').then(res => { this.followers = res.data.followers }) }, computed: { computedFollowers: function () { return this.followers } }, methods:{ printSampleLog(){ this.$store.dispatch('sampleAction').then(res => { this.followers = res.data.followers }) } } }); const store = new Vuex.Store({ actions: { getFollowers() { return new Promise((resolve, reject) => { axios.get('https://api.github.com/users/octocat').then(response => resolve(response)).catch(err => reject(error)) }); }, sampleAction(context){ context.commit('sampleMutation'); } }, mutations: { sampleMutation(){ console.log("sample mutation") } } }) const app = new Vue({ store, el: '#app' })
 <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/vuex"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="app"> <followers></followers> </div>

  • 否则,使用 this.$store.commit() 在您的 Vue 组件中创建不带操作直接提交突变的方法

PS:建议首先围绕突变创建操作,因为它是一种更清洁的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM