有没有专门做根雕的网站数字营销课程
-
使用
watch
监听数据变化:
在子组件中使用watch
来监听父组件传递的数据,一旦数据发生变化,子组件就会重新渲染。子组件代码示例:
<template><div>{{ message }}</div> </template><script> export default {props: {message: {type: String,default: ''}},watch: {message(newVal) {// 当父组件传递的message发生变化时,子组件重新渲染this.$forceUpdate();}} } </script>
-
使用
$emit
和$on
:
在父组件中改变数据后,通过$emit
触发一个事件,然后在子组件中使用$on
监听这个事件,并在事件处理函数中调用$forceUpdate()
来强制子组件重新渲染。父组件代码示例:
<template><child :message="message" @update="updateChild" /> </template><script> import Child from '@/components/Child.vue';export default {components: {Child},data() {return {message: 'Hello'};},methods: {updateChild() {this.message = 'World'; // 改变数据触发子组件重新渲染}} } </script>
子组件代码示例:
<template><div>{{ message }}</div> </template><script> export default {props: {message: {type: String,default: ''}},mounted() {this.$root.$on('update', this.update);},methods: {update() {this.$forceUpdate(); // 强制重新渲染}},beforeDestroy() {this.$root.$off('update', this.update);} } </script>
-
使用
v-if
或v-show
:
通过切换子组件的v-if
或v-show
条件,可以实现子组件的重新渲染。这种方法比较简单,但可能会导致组件频繁地销毁和重建。父组件代码示例:
<template><child :message="message" v-if="showChild" @update="toggleChild" /> </template><script> import Child from '@/components/Child.vue';export default {components: {Child},data() {return {message: 'Hello',showChild: true};},methods: {toggleChild() {this.showChild = !this.showChild; // 切换显示状态以重新渲染子组件}} } </script>