javascript - 如何在模板中使用返回值的函数? View , View

标签 javascript vue.js vuex

我正在使用模板获取 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”,但我希望使用函数 {{ year(item.date) }} 打印“2021”

使用 javascript 编写函数 year() 代码:

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

我试过使用那个代码但是不工作,出现这个错误: this image show error

那是我的 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');
      }
});

最佳答案

在模板中,您可以使用定义为 methods 的函数或 computed .从技术上讲,您还可以使用 data将函数传递给模板,但我不推荐这样做。并不是说它行不通,而是 Vue 在 data 中声明了任何内容reactive 并且使函数(基本上是常数)具有反应性是没有意义的。所以,在你的情况下:

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>

如果出于某种原因,你想通过 year作为computed :

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

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


如果您要导入 year来自另一个文件的函数:

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
}

旁注:

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

关于javascript - 如何在模板中使用返回值的函数? View , View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65373510/

相关文章:

javascript - 如何确定两个 ES6 类实例是否相等?

javascript - 是否有一个 native 函数来获取 javascript 中的前缀数字?

javascript - Vue.js、Vuex 与 Promises

javascript - 如何修复无法安装组件: template or render function not defined in vue

javascript - JS : String. 原型(prototype).toUnderscore()

javascript - 将 html 文件转换为 vue.js

javascript - NuxtJS页面标题不变

Vue.js 如何以百分比设置 block 宽度,具有百分比变量?

vue.js - 如何在 Vue.js 应用程序中使用本地版本的数据对象?

javascript - 每次输入字符时输入表单都会失去焦点