如何在模板中使用 return 值的函数?视图,视图
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() 来修改此信息和 return 和结果,例如:
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” }
代码函数 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');
}
});
我看到您正在尝试使用 Vuex 商店。并在模板语法中使用变异。
不确定我们是否可以像您那样通过 HTML 直接调用突变。过去当我尝试调用突变时,我会:
- 创建一个将提交该突变的操作,并通过 Vue 调用包装在方法中的操作,如下所示:look for a method printSampleLog() that I defined here
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>
- Else 在您的 Vue 组件中创建方法 w/o 操作,使用 this.$store.commit()
直接提交突变
PS:建议首先围绕突变创建操作,因为这是一种更简洁的方法。
在模板中,您可以使用定义为 methods
或 computed
的函数。从技术上讲,您还可以使用 data
将函数传递给模板,但我不推荐这样做。并不是说它行不通,而是 Vue 使 data
中声明的任何内容都具有反应性,并且使函数(基本上是常量)具有反应性是没有意义的。所以,在你的情况下:
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
,因为它是最直接的(易于 read/understand)。
如果您从另一个文件导入 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
}
旁注:
- 遍历包含
<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">
。键帮助 Vue maintain the state 列表元素,跟踪动画并正确更新它们
我正在使用模板获取 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() 来修改此信息和 return 和结果,例如:
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” }
代码函数 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');
}
});
我看到您正在尝试使用 Vuex 商店。并在模板语法中使用变异。
不确定我们是否可以像您那样通过 HTML 直接调用突变。过去当我尝试调用突变时,我会:
- 创建一个将提交该突变的操作,并通过 Vue 调用包装在方法中的操作,如下所示:look for a method printSampleLog() that I defined here
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>
- Else 在您的 Vue 组件中创建方法 w/o 操作,使用 this.$store.commit() 直接提交突变
PS:建议首先围绕突变创建操作,因为这是一种更简洁的方法。
在模板中,您可以使用定义为 methods
或 computed
的函数。从技术上讲,您还可以使用 data
将函数传递给模板,但我不推荐这样做。并不是说它行不通,而是 Vue 使 data
中声明的任何内容都具有反应性,并且使函数(基本上是常量)具有反应性是没有意义的。所以,在你的情况下:
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
,因为它是最直接的(易于 read/understand)。
如果您从另一个文件导入 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
}
旁注:
- 遍历包含
<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">
。键帮助 Vue maintain the state 列表元素,跟踪动画并正确更新它们