跳到主要内容

刷新组件

通过 forceUpdate 刷新组件

原理

通过调用 this.$forceUpdate() 可以重新调用 render() 函数,对数据重新进行响应式绑定。

this.$forceUpdate() 触发 beforeUpdate 和 updated 生命周期

场景

  • v-for 循环或者 某个操作 对 data 数据进行增加、修改、删除操作,此时 data 数据的由于某些原因可能不会引起视图的更新,这时可以通过 this.$forceUpdate()

    :::details 点击查看代码

    <template>
    <div class="home">
    <div class='list'>
    <div class="item" v-for='item in list' :key='item'>{{item}}</div>
    </div>
    <button @click='changeData'>改变</button>
    </div>
    </template>

    <script>
    export default {
    name: "Home",
    components: {},
    data() {
    return {
    list:[
    '我',
    '是',
    '一',
    '颗',
    '小',
    ]
    };
    },
    mounted(){
    console.log('mounted');
    },
    beforeUpdate(){
    console.log('beforeUpdate');
    },
    updated(){
    console.log('updated');
    },
    methods: {
    changeData(){
    this.list[2]='不';
    this.$forceUpdate();
    }
    },
    };
    </script>

    :::

通过 v-if 刷新组件

原理

通过 v-if 控制组件的加载与销毁,触发组件完整地生命周期

场景

  • Home.vue :::details 点击查看代码
<template>
<div class="home">
<button @click="show=!show">显示与影藏 Child组件</button>
<Child v-if="show"></Child>
</div>
</template>

<script>
import Child from "./child.vue";
export default {
name: "Home",
components: {
Child,
},
data() {
return {
show: false,
};
},
};
</script>

:::

  • Child.vue :::details 点击查看代码
<template>
<div class="child">
<input type="text" v-model='form.name'>
</div>
</template>

<script>
export default {
components: {},
data() {
return {
form:{
name:'张文强'
}
};
},
};
</script>

<style lang="scss" scoped></style>

:::

通过 key 刷新组件

原理

通过 key 对子组件或者元素加上一个标识,如果标识改变,Vue 会对其作出刷新的操作 ,同时触发组件的完整生命周期

实现

  • Home.vue :::details 点击查看代码
<template>
<div class="home">
<button @click="key++">改变</button>
<Child :key="key"></Child>
</div>
</template>

<script>
import Child from "./child";
export default {
name: "Home",
components: {
Child,
},
data() {
return {
key: 0,
};
},
mounted() {
console.log("mounted");
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
methods: {
changeData() {
this.list[2] = "不";
this.$forceUpdate();
},
},
};
</script>

:::

  • Child.vue :::details 点击查看代码
<template>
<div class="child">
<input type="text" v-model="form.name" />
</div>
</template>

<script>
export default {
components: {},
data() {
return {
form: {
name: "张文强",
},
};
},
created(){
console.log('created');
},
mounted(){
console.log('mounted');
},
updated(){
console.log('updated');
}
};
</script>

:::