其他分享
首页 > 其他分享> > Vue-强制刷新

Vue-强制刷新

作者:互联网

1、key-changing(最好)

        使用key标记组件身份,当key改变时释放原始组件,重新加载新的组件。

<template>
    <div :key="key">
        <div>{{val}}</div>
        ...
    </div>
</template>
<script>
    export default {
        data() {
            return {
                key: 0
            };
        },
        props: ["val"],
        watch: {
            val() {
                this.key += 1;
            }
        },
    }
</script>

2、this.$forceUpdate(推荐)

<template>
    <button @click="reload">刷新当前组件</button>
</template>
<script>
    export default {
        methods: {
            reload() {
                this.$forceUpdate();
            }
        }
    }
</script>

3、使用v-if标记(不推荐)

        使用watch监测值的变化,配合this.$nextTick使用

<template>
    <div :key="key">
        <div v-if="isShow">{{val}}</div>
        ...
    </div>
</template>
<script>
    export default {
        data() {
            return {
                isShow: true,
            };
        },
        props: ["val"],
        watch: {
            val() {
                this.isShow = false;
                this.$nextTick(()=>{
                    this.isShow = true;
                })
            }
        },
    }
</script>

4、刷新整个页面(不推荐)

        刷新整个页面:体验感不好,一般不建议使用

//其中两个刷新整个页面的方法
window.location.reload();
this.$router.go(0);

标签:Vue,val,isShow,export,key,刷新,组件,强制
来源: https://blog.csdn.net/qq_40007317/article/details/119275304