간단한 질문입니다.
당신은 강제 Vue.js
로 다시로드 / 새로 고침 모든? 그렇다면 어떻게?
간단한 질문입니다.
당신은 강제 Vue.js
로 다시로드 / 새로 고침 모든? 그렇다면 어떻게?
답변:
이 마법 주문을보십시오 :
vm.$forceUpdate();
교수형 변수를 만들 필요가 없습니다. :)
업데이트 : VueJS로 작업하기 시작했을 때이 솔루션을 찾았습니다. 그러나 추가 조사를 통해 이러한 접근 방식을 목발로 입증했습니다. 내가 기억하는 한, 나는 그것을 자동으로 새로 고치지 못한 모든 속성 (대부분 중첩 된 속성)을 계산 된 속성에 넣는 것을 제거했습니다.
자세한 정보는 여기 : https://vuejs.org/v2/guide/computed.html
$forceUpdate()
으로 2.5.17에서 결코 나를 위해 일한 적이 없습니다.
이것은 이 문제 에 대한 matthiasg 의 매우 깨끗한 솔루션처럼 보입니다 .
:key="someVariableUnderYourControl"
구성 요소를 완전히 재구성하려는 경우 키를 사용 하고 변경할 수도 있습니다
내 유스 케이스의 경우 Vuex getter를 소품으로 구성 요소에 공급했습니다. 어쨌든 Vuex는 데이터를 가져 오지만 구성 요소를 다시 렌더링하기 위해 반응성이 안정적으로 시작되지는 않습니다. 필자의 경우 key
소품에서 속성을 일부 속성으로 설정하면 게터 (및 속성)가 마침내 해결 될 때 새로 고침이 보장됩니다.
mounted
실행될 것입니다)
... 강제 업데이트 가 필요 합니까?
아마도 Vue를 최대한 활용하지 않을 것입니다.
Vue 가 값 변경에 자동으로 반응하도록하려면 객체를 처음에로 선언
data
해야합니다 . 또는 그렇지 않은 경우을 사용하여 추가Vue.set()
해야합니다 .
아래 데모에서 의견을 참조하십시오. 또는 여기 에서 JSFiddle 에서 동일한 데모를 여 십시오 .
new Vue({
el: '#app',
data: {
person: {
name: 'Edson'
}
},
methods: {
changeName() {
// because name is declared in data, whenever it
// changes, Vue automatically updates
this.person.name = 'Arantes';
},
changeNickname() {
// because nickname is NOT declared in data, when it
// changes, Vue will NOT automatically update
this.person.nickname = 'Pele';
// although if anything else updates, this change will be seen
},
changeNicknameProperly() {
// when some property is NOT INITIALLY declared in data, the correct way
// to add it is using Vue.set or this.$set
Vue.set(this.person, 'address', '123th avenue.');
// subsequent changes can be done directly now and it will auto update
this.person.address = '345th avenue.';
}
}
})
/* CSS just for the demo, it is not necessary at all! */
span:nth-of-type(1),button:nth-of-type(1) { color: blue; }
span:nth-of-type(2),button:nth-of-type(2) { color: red; }
span:nth-of-type(3),button:nth-of-type(3) { color: green; }
span { font-family: monospace }
<script src="https://unpkg.com/vue"></script>
<div id="app">
<span>person.name: {{ person.name }}</span><br>
<span>person.nickname: {{ person.nickname }}</span><br>
<span>person.address: {{ person.address }}</span><br>
<br>
<button @click="changeName">this.person.name = 'Arantes'; (will auto update because `name` was in `data`)</button><br>
<button @click="changeNickname">this.person.nickname = 'Pele'; (will NOT auto update because `nickname` was not in `data`)</button><br>
<button @click="changeNicknameProperly">Vue.set(this.person, 'address', '99th st.'); (WILL auto update even though `address` was not in `data`)</button>
<br>
<br>
For more info, read the comments in the code. Or check the docs on <b>Reactivity</b> (link below).
</div>
Vue의이 부분을 마스터하려면 반응성 -변경 감지주의 사항 에 대한 공식 문서를 확인하십시오 . 반드시 읽어야합니다!
Vue.set()
수도 있지만 예, 구성 요소 내부에서도 작동합니다.
이 http://michaelnthiessen.com/force-re-render/를 읽으십시오
끔찍한 방법 : 전체 페이지를 새로 고침
끔찍한 방법 : v-if 핵 사용하기
더 좋은 방법 : Vue의 내장 forceUpdate 방법
사용하기 가장 좋은 방법 : 컴포넌트에서 키 변경
<template>
<component-to-re-render :key="componentKey" />
</template>
<script>
export default {
data() {
return {
componentKey: 0,
};
},
methods: {
forceRerender() {
this.componentKey += 1;
}
}
}
</script>
또한 상황에 따라 watch :를 사용합니다.
this.$router.go(0);
현재 페이지를 수동으로 다시로드하는 데 사용 하십시오.
사용하십시오 vm.$set('varName', value)
. Change_Detection_Caveats 에서 세부 사항을 찾으십시오 .
물론 .. 키 속성을 사용하여 언제든지 다시 렌더링 (복제) 할 수 있습니다.
<mycomponent :key="somevalueunderyourcontrol"></mycomponent>
예제는 https://jsfiddle.net/mgoetzke/epqy1xgf/ 를 참조 하십시오.
https://github.com/vuejs/Discussion/issues/356#issuecomment-336060875 에서도 논의되었습니다.
<my-component :key="uniqueKey" />
그것과 함께 모든 업데이트에 대한 객체 (obj) 값의 모든 업데이트에 대해 사용 this.$set(obj,'obj_key',value)
및 uniqueKey
업데이트this.uniqueKey++
그것은 이런 식으로 나를 위해 일했다
이 작업을 수행 할 수있는 두 가지 방법이 있습니다.
1). $forceUpdate()
메소드 핸들러 내부에서 사용할 수 있습니다.
<your-component @click="reRender()"></your-component>
<script>
export default {
methods: {
reRender(){
this.$forceUpdate()
}
}
}
</script>
2). :key
다시 렌더링하고 싶을 때 구성 요소에 속성을 부여 하고 무례하게 할 수 있습니다
<your-component :key="index" @click="reRender()"></your-component>
<script>
export default {
data() {
return {
index: 1
}
},
methods: {
reRender(){
this.index++
}
}
}
</script>
: key = "$ route.params.param1"은 자동 재로드 하위 항목을 매개 변수와 함께 키를 사용합니다.
다른 탭의 변경 사항으로 인해 다시 렌더링하려는 이미지 갤러리 에서이 문제가 발생했습니다. 따라서 tab1 = imageGallery, tab2 = favoriteImages
tab @ change = "updateGallery ()"-> 이렇게하면 탭을 전환 할 때마다 v-for 지시문이 필터링 된 이미지 함수를 처리합니다.
<script>
export default {
data() {
return {
currentTab: 0,
tab: null,
colorFilter: "",
colors: ["None", "Beige", "Black"],
items: ["Image Gallery", "Favorite Images"]
};
},
methods: {
filteredImages: function() {
return this.$store.getters.getImageDatabase.filter(img => {
if (img.color.match(this.colorFilter)) return true;
});
},
updateGallery: async function() {
// instance is responsive to changes
// change is made and forces filteredImages to do its thing
// async await forces the browser to slow down and allows changes to take effect
await this.$nextTick(function() {
this.colorFilter = "Black";
});
await this.$nextTick(function() {
// Doesnt hurt to zero out filters on change
this.colorFilter = "";
});
}
}
};
</script>
페이지 다시로드 방법 (깜박임)을 제외하고는 죄송합니다. 아무 것도 작동하지 않습니다 (: 키가 작동하지 않음).
그리고 나는 오래된 vue.js 포럼 에서이 방법을 찾았습니다.
https://github.com/vuejs/Discussion/issues/356
<template>
<div v-if="show">
<button @click="rerender">re-render</button>
</div>
</template>
<script>
export default {
data(){
return {show:true}
},
methods:{
rerender(){
this.show = false
this.$nextTick(() => {
this.show = true
console.log('re-render start')
this.$nextTick(() => {
console.log('re-render end')
})
})
}
}
}
</script>