템플릿 내에서 값을 반환하는 기능을 사용하는 방법브룩스, 브룩스
템플릿을 사용하여 json 파일의 데이터를 가져오는 중이고 "v-for"를 사용하여 모든 데이터(예:
template: /*html*/
`
<div class="col-lg-8">
<template v-for="item of actividades">
<ul>
<li>{{ item.date }}</li>
<ul>
</template>
</div>
`,
그러나 나는 이 정보를 수정하기 위해 연도()를 사용하고, 예를 들어 다음과 같은 결과를 얻어야 한다.
template: /*html*/
`
<div class="col-lg-8">
<template v-for="item of actividades">
<ul>
<li>{{ year(item.date) }}</li>
<ul>
</template>
</div>
`,
값 {{항목.date }}}은(는) "2021-01-20"으로 인쇄하지만, {{년(항목.date)}}기능을 이용하여 "2021"으로 인쇄하길 바란다.
Javascript를 사용한 코드 기능 연도():
year(date){
return String(date).substr(0, 4);
}
코드를 사용하려고 했지만 작동하지 않는 경우 다음 오류가 표시됨:
그게 내 자바스크립트 코드야
//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
템플릿에 기능을 전달하기 위해. 하지만 난 추천하지 않아.효과가 없을 거라는 건 아니지만, 부에가 선언하는 건 뭐든지 해.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); }
}
그러나 그것은 복잡한 구조(내부 화살표 함수를 반환하는 게터 함수)이며, 이 복잡성은 아무런 목적도 제공하지 않는다.A를 사용하는 것을 추천한다.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를 직접 v-for에 설치하면<ul>
그리고 잃어버리다.<template>
(사용만 하십시오.<template>
어떤 논리를 적용하고 싶을 때 - 즉: av-if
- 실제로 DOM 포장지로 포장하지 않고 여러 요소에 적용. 또 다른 사용 사례는 자녀가 부모의 직계 자손이 되기를 원하는 경우:<ul>
/<li>
또는<tbody>
/<tr>
중간 포장지를 사이에 둘 수 없는 관계).당신 같은 경우, 그 자리에v-for
에서<ul>
더 적은 코드로 정확하게 동일한 결과를 생성한다. - 너는 항상 그래야 한다.
key
당신의v-for
의:<ul v-for="(item, key) in actividades" :key="key">
키는 Vue가 목록 요소의 상태를 유지하고 애니메이션을 추적하고 올바르게 업데이트하는 데 도움이 된다.
나는 네가 Vuex 상점에서 일하려고 노력하고 있다는 것을 알았다.템플릿 구문 내에 돌연변이를 사용하는 경우.
우리가 HTML을 통해 당신이 하는 것처럼 변이를 직접 부를 수 있을지 확실하지 않다.과거에 돌연변이를 부르려고 했을 때, 나는 어느 쪽이든:
- 돌연변이를 발생시키는 작업을 생성하고 Vue를 통해 메서드 안에 포함된 작업을 호출하십시오.여기서 정의한 메서드 printSampleLog()를 찾으십시오.
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>
- 그렇지 않으면 이를 사용하여 Vue 구성 요소에서 직접 돌연변이를 커밋하는 작업이 있는 메서드를 생성하십시오.$store.committe
PS: 돌연변이가 훨씬 더 깨끗한 방법이기 때문에, 먼저 돌연변이를 중심으로 행동을 만들 것을 권하고 싶다.
'programing' 카테고리의 다른 글
Java 8 어레이에서 스트림 및 작동 (0) | 2022.04.26 |
---|---|
C와 C++에서 거의 동일한 코드 간의 실행 시간에서 큰 차이(x9) (0) | 2022.04.26 |
null을 ternary 연산자에 허용된 int로 반환하지만 문이 아닌 경우 (0) | 2022.04.26 |
Vuex 업데이트 상태 (0) | 2022.04.26 |
Enum과 Define 문 간의 차이 (0) | 2022.04.26 |