Vue.js에게 강제로 재장전/재장전할 수 있는가?
그냥 간단한 질문이야.
강제할 수 있나?Vue.js
모든 걸 재장전할 수 있을까?만약 그렇다면, 어떻게?
마법 주문 사용:
vm.$forceUpdate();
//or in file components
this.$forceUpdate();
매달려 있는 var를 만들 필요가 없음 :)
업데이트: VueJS와 함께 작업할 때만 이 솔루션을 찾았어.그러나 더 이상의 탐사는 이 접근법을 목발처럼 증명했다.내가 기억하기로는, 얼마 지나지 않아 나는 그것을 없앴다. 자동으로 새로 고치지 못한 모든 속성(대부분 중첩된 속성)을 계산된 속성에 넣기만 하면 된다.
자세한 내용은 https://vuejs.org/v2/guide/computed.html를 참조하십시오.
이것은 이 문제에 대한 matthiasg의 꽤 깨끗한 해결책처럼 보인다.
당신은 또한 사용할 수 있다.
:key="someVariableUnderYourControl"
구성 요소를 완전히 재구성하려면 키를 변경하십시오.
내 사용 사례로, 나는 부익스 게이터를 소품으로 구성 요소에 공급하고 있었다.Vuex는 어떻게든 데이터를 가져오겠지만 반응성은 그 구성 요소를 다시 렌더링하기 위해 안정적으로 투입되지 않았다.내 경우 구성 요소 설정key
getter(및 속성)가 최종적으로 해결되었을 때, 소포의 일부 속성에 대한 업데이트/교체를 보장한다.
이 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>
나는 또한 시계를 사용한다: 어떤 상황에서는.
왜?
...업데이트를 강제할 필요가 있는가?
아마도 당신은 최선을 다해서 Vue를 탐구하고 있지 않을 것이다.
Vue가 값 변경에 자동으로 반응하도록 하려면 객체를 초기 에 선언해야 하며 그렇지 않으면 를 사용하여 객체를 추가해야 한다.
아래 데모에서 설명을 참조하십시오.또는 여기서 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의 이 부분을 숙달하려면 반응성에 대한 공식 문서 - 변경 탐지 주의사항을 확인하십시오.그것은 꼭 읽어야 할 책이다!
사용 시도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" />
사용과 함께.this.$set(obj,'obj_key',value)
업데이트 및 업데이트uniqueKey
모든 업데이트에 대한 개체(obj) 값의 모든 업데이트에 대해this.uniqueKey++
내게는 이런 식으로 작용했다.
그러니 두 가지 방법이 있어
- 사용할 수 있다
$forceUpdate()
당신의 메서드 핸들러 안에.
<your-component @click="reRender()"></your-component>
<script>
export default {
methods: {
reRender(){
this.$forceUpdate()
}
}
}
</script>
- A를 줄 수 있다.
:key
, (rerendery)의(rerendery의 .
<your-component :key="index" @click="reRender()"></your-component>
<script>
export default {
data() {
return {
index: 1
}
},
methods: {
reRender(){
this.index++
}
}
}
</script>
구성 요소를 다시 로드/재렌더/새로 고치려면 긴 코딩을 중지하십시오.부에가 있다.JS 방식.
그냥 사용해:key
기여하다
예를 들면 다음과 같다.
<my-component :key="unique" />
BS Vue Table Slot에 있는 것을 사용하고 있다.내가 이 부품을 위해 무언가를 할 것이라고 말하니, 그것을 독특하게 만들어라.
v-if 지시어 사용
<div v-if="trulyvalue">
<component-here />
</div>
따라서 단순히 진실한 가치의 가치를 거짓에서 참으로 변화시킴으로써 디브 사이의 구성요소가 다시 렌더링하게 될 것이다.
이것은 나에게 효과가 있었다.
created() {
EventBus.$on('refresh-stores-list', () => {
this.$forceUpdate();
});
},
다른 구성 요소에서 refresh-store-list 이벤트를 실행하면 현재 구성 요소가 리렌더됨
방법을 찾았어.그것은 좀 진부하지만 효과가 있다.
vm.$set("x",0);
vm.$delete("x");
어디에vm
의 뷰 뷰 모델 객체,x
존재하지 않는 변수다.
Vue.js는 콘솔 로그에서 이에 대해 불평할 것이지만 모든 데이터에 대해 새로 고침을 트리거한다.버전 1.0.26으로 테스트.
나를 위해 일했다.
data () {
return {
userInfo: null,
offers: null
}
},
watch: {
'$route'() {
this.userInfo = null
this.offers = null
this.loadUserInfo()
this.getUserOffers()
}
}
<router-view :key="$route.params.slug" />
키와 함께 임의의 매개 변수를 사용하여 자식 자동 다시 로드하십시오.
2021년 12월 업데이트:
:key="$route"를 추가하여 구성요소를 강제 재로드할 수 있다.전체 경로".
하위 구성 요소의 경우:
<Child :key="$route.fullPath" />
라우터 보기 태그의 경우:
<router-view :key="$route.fullPath" />
그러나 :key="$route.fullPath"는 다른 경로의 구성요소를 강제로 재로드할 수 있을 뿐 동일한 경로의 구성요소는 로드할 수 없다.같은 경로의 구성요소를 강제로 재적재할 수 있으려면 :key="$route"에 어레이와 함께 "value"를 추가해야 한다.fullPath" 및 "value(값) 변경.그래서 :key="[$route]가 된다."fullPath, value]" 그리고 우리는 "value"를 바꿔야 한다.
*배열을 :key=에 할당할 수 있다.
<template>
<Child
:key="[$route.fullPath, value]" // Can assign "Array" to ":key="
@childReload="reload" // Call @click="$emit('childReload')" in
/> // Child Component to increment the value.
</template>
OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR
<template>
<router-view
:key="[$route.fullPath, value]" // Can assign "Array" to ":key="
@routerViewReload="reload" // Call @click="$emit('routerViewReload')"
/> // in Child Component to increment the value.
</template>
<script>
export default {
name: "Parent", components: { Child, },
data() {
return {
value: 0,
};
},
methods: {
reload() {
this.value++;
}
}
}
</script>
그러나, 계속 "$route"를 사용한다.fullPath 및 "value"는 때때로 오류를 유발하므로 클릭과 같은 이벤트가 발생할 때만 "$route"를 모두 사용하십시오.전체 경로" 및 "값".클릭과 같은 이벤트가 발생하면 항상 "$route"만 사용하면 된다.전체 경로".
최종 암호는 다음과 같다.
<template>
<Child
:key="state ? $route.fullPath : [$route.fullPath, value]"
@childReload="reload" // Call @click="$emit('childReload')" in
/> // Child Component to increment the value.
</template>
OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR OR
<template>
<router-view
:key="state ? $route.fullPath : [$route.fullPath, value]"
@routerViewReload="reload" // Call @click="$emit('routerViewReload')" in
/> // Child Component to increment the value.
</template>
<script>
export default {
name: "Parent", components: { Child, },
data() {
return {
state: true,
value: 0,
};
},
methods: {
reload() {
this.state = false;
this.value++;
this.$nextTick(() => this.state = true);
}
}
}
</script>
불행히도 Vue에서는 구성요소를 적절히 강제 재로드할 수 있는 간단한 방법이 없다.지금으로서는 그게 부에의 문제다.
추가하는 방법:key
vue-parents lib's에.router-view
컴포넌트 원인에 대한 불안감이 나를 괴롭히기 때문에, 나는 뷰루터의 '인 컴포넌트 가드'에 가서 업데이트를 가로채고, 같은 경로($router.go, $router)의 경로 업데이트가 있을 때 그에 따라 페이지 전체를 새로 고쳤다.푸시, $185는 도움이 되지 않았다.)이것과 관련된 유일한 주의사항은 우리가 페이지를 새로 고침으로써 싱글 페이지 앱의 행동을 잠시 중단해야 한다는 것이다.
beforeRouteUpdate(to, from, next) {
if (to.path !== from.path) {
window.location = to.path;
}
},
페이지 다시 로드 방법(슬릭링)을 제외하면 어느 것도 나에게 효과가 없다(:키로는 작동하지 않았다).
그리고 나는 이 방법을 나에게 효과가 있는 오래된 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>
다음 코드 추가:
this.$forceUpdate()
아직 주위를 둘러보는 사람들을 위해, 지금 이것을 위한 소포가 있다.
https://github.com/gabrielmbmb/vuex-multi-tab-state
main.ts(저 페이지에 나와 있는 것처럼)의 플러그인에 설치해서 추가하기만 하면 되는 것인데, 그것은 내가 원하는 대로 정확히 작동했다.
참조URL: https://stackoverflow.com/questions/32106155/can-you-force-vue-js-to-reload-re-render
'Programing' 카테고리의 다른 글
Google 글꼴 사전 로드 (0) | 2022.04.09 |
---|---|
Nuxt TTFB 향상 (0) | 2022.04.09 |
소품 포함 Vue-Router 전달 데이터 (0) | 2022.04.09 |
Vuex 작업에서 약속 반환 (0) | 2022.04.09 |
왜 분할이 정수로 반올림되는가? (0) | 2022.04.09 |