Vue에서 계산된 속성이 감시를 트리거하지 않습니다.
이 게시물에 따르면 계산된 속성을 보는 것은 문제가 되지 않을 것입니다.하지만 내 코드가 먹혀들지 않아
<template>
<div v-if="product" class="section">
<form>
<div class="control"><input type="text" class="input" v-model="title"></div>
<div class="control"><input type="text" class="input" v-model="description"></div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
title: null,
description: null
}
},
computed: {
product() {
// const payload = { collection: 'products', id: this.$route.params.productId }
// return this.$store.getters.objectFromId(payload)
console.log('working')
return { title: 'Awesome Title', description: 'Awesome Description' }
}
},
watch: {
product() {
this.title = this.product.title,
this.description = this.product.description
}
}
}
</script>
기대하겠습니다.watch
촉발하다product
반환되지만 반환되지 않습니다.
다음과 같이 계산된 속성에서 속성을 설정할 수 있습니다.
computed: {
product() {
const payload = { collection: 'products', id: this.$route.params.productId }
const product = this.$store.getters.objectFromId(payload)
this.title = product.title
this.description = product.description
return product
}
}
그런데 컴파일러가 경고합니다.error: Unexpected side effect in "product" computed property
OP의 코멘트에 의하면, 그의 의도는 초기 데이터를 입수해 로드하는 것입니다.이 동작을 실현하는 일반적인 방법은 내부에 배치하는 것입니다.created or mounted
vuejs 라이프 사이클 훅
<template>
<div v-if="product" class="section">
<form>
<div class="control"><input type="text" class="input" v-model="title"></div>
<div class="control"><input type="text" class="input" v-model="description"></div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
title: '',
description: ''
}
},
created() {
this.getInitialData();
this.foo();
console.log("created!");
},
methods: {
getInitialData: function(){
const payload = {
collection: 'products',
id: this.$route.params.productId
};
var product = this.$store.getters.objectFromId(payload);
this.title = product.title;
this.description = product.description;
},
foo: function(){// ...}
},
}
</script>
당신 구조가 좀 엉망진창이네요. product
는 계산되어 있기 때문에 소스 값이 변경될 때마다 실행됩니다.(실행 시기를 제어할 수 없습니다.)부작용이 있어서는 안 된다(할당).this.description
,this.title
또는 네트워크 요청을 트리거합니다.
의 코드product
소스 데이터를 가져오는 중입니다.이것은 에 속합니다.methods
사용자 액션 또는 라이프 사이클이벤트에 명시적으로 링크되어 있습니다.
데이터를 복사해야 하는 이유(this.description = product.description
에watch:product
)? Vue는 Vue 외부에 있는 데이터(앱 상태)가 글로벌 변수인 경우에 가장 적합합니다.Vue 컴포넌트는 특정 순간의 앱 상태에 관계없이 투명하게 반영됩니다.
이게 도움이 됐으면 좋겠다.
다음을 시도해 보십시오.
watch: {
product: {
immediate: true,
handler(value) {
updateCode();
}
}
}
언급URL : https://stackoverflow.com/questions/51459600/computed-property-in-vue-is-not-triggering-a-watch
'programing' 카테고리의 다른 글
C에서 어레이만 포함하는 구조를 선언하는 이유는 무엇입니까? (0) | 2022.08.24 |
---|---|
어레이에서 구성 요소 삭제, vuejs에서 잘못된 구성 요소 제거 (0) | 2022.08.24 |
FetchType을 가져오는 방법.스프링 컨트롤러에서 JPA 및 휴지 상태와의 LAGY 관련성 (0) | 2022.08.24 |
'in' 연산자를 사용하여 정의되지 않은 'X'를 검색할 수 없습니다. (0) | 2022.08.24 |
지원되지 않거나 구현되지 않은 작업에 대해 Java에서 발생하는 표준 예외는 무엇입니까? (0) | 2022.08.24 |