this.$forceUpdate 在 Vue 3 中等效 - 组合 API?
this.$forceUpdate equivalent in Vue 3 - Composition API?
在 Vue 2 中,实例方法 this.$forceUpdate()
可用于手动更新组件。我们如何强制更新 Vue 3 中的组件 - Composition API(内部设置方法)?
setup(props, context) {
const doSomething = () => {
/* how to call $forceUpdate here? */
}
return {
doSomething
}
}
提前致谢。
当我需要在 vue 中强制更新时,我通常会添加一个具有我可以更改的值的键,然后这将强制 vue 更新它。这也应该适用于 vue 3,尽管我承认我从未尝试过。这是一个例子:
<template>
<ComponentToUpdate
:key="updateKey"
/>
</template>
<script>
export default {
data() {
return {
updateKey: 0,
};
},
methods: {
forceUpdate() {
this.updateKey += 1;
}
}
}
</script>
您可以在此处阅读更多相关信息:https://michaelnthiessen.com/key-changing-technique/
$forceUpdate
在 Vue3 中仍然可用,但您将无法在 setup()
函数中访问它。如果你绝对需要使用它,你可以使用 object API 组件或者这个花哨的技巧...
app.component("my-component", {
template: `...`,
methods: {
forceUpdate(){
this.$forceUpdate()
}
},
setup(props) {
const instance = Vue.getCurrentInstance();
Vue.onBeforeMount(()=>{
// instance.ctx is not populated immediately
instance.ctx.forceUpdate();
})
return {doSomething};
},
})
如果这看起来像是一个荒谬的解决方案,请相信您的判断。理想情况下,您的应用程序不会依赖 forceUpdate
。如果你依赖它,它可能意味着配置错误,这应该是首先要解决的问题。
如果使用选项 API:
<script lang="ts">
import {getCurrentInstance, defineComponent} from 'vue'
export default defineComponent({
setup() {
const instance = getCurrentInstance();
instance?.proxy?.$forceUpdate();
}
})
</script>
如果将 Composition API 与
结合使用
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance();
instance?.proxy?.$forceUpdate();
</script>
在 Vue 2 中,实例方法 this.$forceUpdate()
可用于手动更新组件。我们如何强制更新 Vue 3 中的组件 - Composition API(内部设置方法)?
setup(props, context) {
const doSomething = () => {
/* how to call $forceUpdate here? */
}
return {
doSomething
}
}
提前致谢。
当我需要在 vue 中强制更新时,我通常会添加一个具有我可以更改的值的键,然后这将强制 vue 更新它。这也应该适用于 vue 3,尽管我承认我从未尝试过。这是一个例子:
<template>
<ComponentToUpdate
:key="updateKey"
/>
</template>
<script>
export default {
data() {
return {
updateKey: 0,
};
},
methods: {
forceUpdate() {
this.updateKey += 1;
}
}
}
</script>
您可以在此处阅读更多相关信息:https://michaelnthiessen.com/key-changing-technique/
$forceUpdate
在 Vue3 中仍然可用,但您将无法在 setup()
函数中访问它。如果你绝对需要使用它,你可以使用 object API 组件或者这个花哨的技巧...
app.component("my-component", {
template: `...`,
methods: {
forceUpdate(){
this.$forceUpdate()
}
},
setup(props) {
const instance = Vue.getCurrentInstance();
Vue.onBeforeMount(()=>{
// instance.ctx is not populated immediately
instance.ctx.forceUpdate();
})
return {doSomething};
},
})
如果这看起来像是一个荒谬的解决方案,请相信您的判断。理想情况下,您的应用程序不会依赖 forceUpdate
。如果你依赖它,它可能意味着配置错误,这应该是首先要解决的问题。
如果使用选项 API:
<script lang="ts">
import {getCurrentInstance, defineComponent} from 'vue'
export default defineComponent({
setup() {
const instance = getCurrentInstance();
instance?.proxy?.$forceUpdate();
}
})
</script>
如果将 Composition API 与
结合使用<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance();
instance?.proxy?.$forceUpdate();
</script>