vitejs / vite-plugin-vue2

Vite plugin for Vue 2.7
MIT License
551 stars 47 forks source link

fix: update functional components in hmr.reload() #52

Open jonaskuske opened 2 years ago

jonaskuske commented 2 years ago

An SFC functional component that does not use <template functional> will go through __VUE_HMR_RUNTIME__.reload() instead of .rerender(), because the plugin can't detect the functional template attr to inject its _rerender_only marker.

After updating the component's options, the reload function will still try to reload it by updating its parent via $vnode.context. This causes two issues:

  1. For functional components, the instance already points to the component's (stateful) parent. In turn, the functional component's grandparent is updated, which does not cause the functional component down the tree to rerender. (unless props changed) So the update does not appear on the screen until maybe later some other condition causes a rerender:
A (instance.$vnode.context)
  B (instance)
    C (functional component child)

reload(C) ----> A.$forceUpdate() --/XX/--> C rerenders
  1. If the functional component is rendered as child in the root component, then even though not the root but a child was modified, instance will point to the root. The runtime notices that the instance has no parent context (which would be the child's grandparent) and issues a warning about unsupported root HMR instead of updating the child:
A ($vnode.context = undefined)
  App.vue (instance = root)
    C (functional component child)

reload(C) ----> (undefined).$forceUpdate() ----> warning --/XX/--> C rerenders

To fix this, this PR makes __VUE_HMR_RUNTIME__.reload call .$forceUpdate() on the instance itself instead of on the parent context if the reloaded component is functional.