QA
Senior LevelVue JS

How do you write SSR-compatible custom directives by providing getSSRProps in directive definitions?

❓ Interview Prompt: Explain custom directive execution in SSR environment, getSSRProps function, and serializing HTML attributes on server.

Standard custom directives that manipulate DOM nodes directly inside 'mounted(el)' fail during Server-Side Rendering (SSR) because there is no DOM element on the server.

SSR-Compatible Directives:

Provide a 'getSSRProps(binding)' function in your custom directive definition. The server renderer executes 'getSSRProps()' during SSR compilation, returning an object of HTML attributes/styles to be serialized directly into the server HTML string!

Code Implementation Example

javascript
// Custom SSR-compatible Tooltip directive
export const vTooltip = {
  // Client-side DOM hook
  mounted(el, binding) {
    el.setAttribute('title', binding.value);
  },
  // SSR Server-side hook: Serializes attribute directly into server HTML string!
  getSSRProps(binding) {
    return { title: binding.value };
  }
};
💡Defining getSSRProps for SSR-compatible custom directives.
🎯 Interview Key Takeaway

Provide getSSRProps(binding) in custom directive definitions to support Server-Side Rendering HTML attribute serialization.

#Custom Directives#SSR#getSSRProps#Senior
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?