계산된 vue에서 화살표 사용 기능이 작동하지 않음
저는 Vue를 배우고 있는데 연산 속성에서 화살표 함수를 사용하다가 문제가 생겼습니다.
원래의 코드는 정상적으로 동작합니다(아래의 스니펫을 참조).
new Vue({
el: '#app',
data: {
turnRed: false,
turnGreen: false,
turnBlue: false
},
computed:{
switchRed: function () {
return {red: this.turnRed}
},
switchGreen: function () {
return {green: this.turnGreen}
},
switchBlue: function () {
return {blue: this.turnBlue}
}
}
});
.demo{
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.js"></script>
<div id="app">
<div class="demo" @click="turnRed = !turnRed" :class="switchRed"></div>
<div class="demo" @click="turnGreen = !turnGreen" :class="switchGreen"></div>
<div class="demo" @click="turnBlue = !turnBlue" :class="switchBlue"></div>
</div>
그러나 계산된 속성에서 메서드를 변경한 후에는 색상이 변경되지 않습니다(turnRed 값은 true와 false 사이에서 정상적으로 전환됩니다).
코드는 다음과 같습니다.
computed:{
switchRed: () => {
return {red: this.turnRed}
},
switchGreen: () => {
return {green: this.turnGreen}
},
switchBlue: () => {
return {blue: this.turnBlue}
}
}
잘못된 구문을 사용하고 있습니까?
화살표 함수가 바인딩되지 않기 때문에 이 오류가 발생합니다.this
계산된 속성을 정의할 vue 인스턴스로 이동합니다.같은 일이 일어날 것입니다.methods
화살표 기능을 사용합니다.
인스턴스 속성 또는 콜백에 화살표 함수를 사용하지 마십시오(예:
vm.$watch('a', newVal => this.myMethod()))
화살표 함수는 상위 컨텍스트에 바인딩되어 있기 때문에 이는 예상대로 Vue 인스턴스가 아닙니다.this.myMethod
정의되지 않습니다.
여기서 보실 수 있습니다.
화살표 함수로 인해 Vue 구성 요소 컨텍스트가 손실되었습니다.에서의 기능methods
,computed
,watch
오브젝트 함수를 사용합니다.
computed:{
switchRed() {
return {red: this.turnRed}
},
switchGreen() {
return {green: this.turnGreen}
},
switchBlue() {
return {blue: this.turnBlue}
}
}
여기서 원하는 것을 디컨스트럭션함으로써 이를 실현할 수 있습니다.
computed:{
switchRed: ({ turnRed }) => {red: turnRed},
switchGreen: ({ turnGreen }) => {green: turnGreen},
switchBlue: ({ turnBlue }) => {blue: turnBlue}
}
그리고 왜 이렇게 간단한 걸 하지 않는 거죠?
new Vue({
el: '#app',
data: {
turnRed: false,
turnGreen: false,
turnBlue: false
},
methods:{
toggle (color) {
this[`turn${color}`] = !this[`turn${color}`];
}
}
});
.demo{
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.js"></script>
<div id="app">
<div class="demo" @click="toggle('Red')" :class="{red:turnRed}"></div>
<div class="demo" @click="toggle('Green')" :class="{green: turnGreen}"></div>
<div class="demo" @click="toggle('Blue')" :class="{blue: turnBlue}"></div>
</div>
계산 생성 시 사용하지 않음=>
, 를 사용해 주세요.switchRed () {...
토막글을 보세요.정상적으로 동작합니다.
계산된 모든 방법, 관찰자 등에 적용됩니다.
new Vue({
el: '#app',
data: {
turnRed: false,
turnGreen: false,
turnBlue: false
},
computed:{
switchRed () {
return {red: this.turnRed}
},
switchGreen () {
return {green: this.turnGreen}
},
switchBlue () {
return {blue: this.turnBlue}
}
}
});
.demo{
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.js"></script>
<div id="app">
<div class="demo" @click="turnRed = !turnRed" :class="switchRed"></div>
<div class="demo" @click="turnGreen = !turnGreen" :class="switchGreen"></div>
<div class="demo" @click="turnBlue = !turnBlue" :class="switchBlue"></div>
</div>
이것이 나중에 역효과를 낼지는 모르겠지만 vue 객체 속성에 사용된 화살표 함수가 수신됩니다.this
context를 첫 번째 인수로 지정합니다.
props: ['foo'],
data: (ctx) => ({
firstName: 'Ryan',
lastName: 'Norooz',
// context is available here as well like so:
bar: ctx.foo
}),
computed: {
fullName: ctx => ctx.firstName + ' ' + ctx.lastName // outputs: `Ryan Norooz`
}
이렇게 하면 컴포넌트 컨텍스트의 모든 것에 액세스할 수 있습니다.this
!
언급URL : https://stackoverflow.com/questions/42971081/use-arrow-function-in-vue-computed-does-not-work
'programing' 카테고리의 다른 글
Spring Boot에서 SQL 문을 기록하는 방법 (0) | 2022.07.07 |
---|---|
epoll의 에지 트리거링 옵션의 용도는 무엇입니까? (0) | 2022.07.07 |
Java에서 List를 int[]로 변환하려면 어떻게 해야 합니까? (0) | 2022.07.07 |
왜 기억에 쓰는 것이 읽는 것보다 훨씬 느릴까요? (0) | 2022.07.07 |
C/C++ 메인 함수의 파라미터는 어디에 있습니까? (0) | 2022.07.07 |