Vue Slots Jsx

Posted : admin On

TLDR; I show that Vue can use JSX to utilize the React pattern of a render prop. Source code here

  1. Vue Jsx Slot Name
  2. Vue Scoped Slots Jsx
  3. Jsx Vue Slots
  4. Vue V-slot Jsx

In Vue, templates are typically how we compose/extend/mix/open source our components. This is contra the experience of React developers who write most of their compiled html in JSX.

Vue中使用 render写一些展示组件 通过实现一个简单的单元 cell 组件, 来了解render jsx 在vue的使用 将 h 作为 createElement 的别名是 Vue 生态系统中的一个通用惯例,实际上也是 JSX 所要求的。. Vue 3.0对tree-shaking非常友好,所有API和内置组件都支持tree-shaking。 如果你所有地方都没有用到onMounted,支持tree-shaking的打包工具会自动将起去掉,不会打进最后的包里。 指令和过渡效果. Vue 3.0还提供了一系列组件和方法,来使JSX也能使用模板语法的指令和过渡. Vue 2 中,仅仅属性就有三种:组件属性 props,普通 html 属性attrs,DOM 属性 domProps。想要更多了解如何在 Vue 2 中写 JSX 语法,可以看这篇,在 Vue 中使用 JSX 的正确姿势。.

Thanks to a similar architecture of using the virtualDOM + createElement API and babel-plugin-transform-vue-js, we can write our Vue components in almost the same way we write React! (Not that we should do this for all components, but it's fun to see design patterns and utilize them).

Vue Jsx Slot Name

UPDATE: I'm using render props in https://github.com/educents/vue-autosuggest in the renderSuggestion prop, so go check it out!

  1. 渲染函数 & JSX — Vue.jsrender函数特点render函数和模板一样,模板可以做的事情它都可以做render函数是最接近编译器的函数render函数返回vnode模板和jsx会先编译成render函数然后在返回vnode组件树中的所有 V.
  2. Vue.js - The Progressive JavaScript Framework. Each Vue instance goes through a series of initialization steps when it’s created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.

Render props demo

For demonstration, I will use an example from Use a Render Prop! article by Michael Jackson.

First the SFC:

Here in our parent App.vue, the Mouse component will be our child component. Inside Mouse.js we will call our renderProp function callback inside the render method. I've mixed JSX inside the SFC's methods section as you can't use jsx inside template. Here's our Mouse component:

Yes this is a Vue component, not React. Compared with the React version:

Some differences between the two:

  • Vue has built in prop type validation.
  • You can't inline an anonymous function that returns jsx inside a template. I've named the callback __render(A single _ before render also throws a Vue warning). You can reasonably use a simple Vue .js component as the parent to pass in an anonymous function, but alas, we're Vue developers so we can mix our templates with our JSX and be happy about it!
  • We're passing back this (the Vue instance) instead of the React state, but utilize destructuring all the same to pass back x and y.
  • The obvious Vue differences such as components are just objects, not javascript classes, there is no 'setState' as it converts it's Reactive data properties (the corollary to React's state) to getter/setters using Object.defineProperty.
  • onMouseMove vs onMousemove 💣

Vue Render Prop

So there you go, a fairly similar and transferable component design.

Never miss a new post!

Get our latest post in your inbox every Tuesday by subscribing to the Vue.js Developers Newsletter .

This subscription also includes Vue.js Developers promotional emails. You can opt-out at any time. View our privacy policy .

This form is protected by reCAPTCHA. The Google privacy policy and terms of service apply.

Scoped Slots

In case you are wondering what's the equivalent pattern in Vue, it's called scoped slots (and if using JSX it works the same as React)

— Evan You (@youyuxi) September 25, 2017

Vue creator Evan You on render props.

If you were to do 'render props' with templates, a similar design would be to use scoped slots and would look something like this:

Vue Scoped slots are powerful when using templates.

Slot

Some advantages to scoped slots are that:

  • Custom parent-child template injection without a render function or jsx.
  • You can specify default content easily. In the above example, I pass in a specified slot, that defines a custom message, but when I don't specify a slot, it will fallback to the default slot. A default slot also gives users of the component a 'component api' so that you don't have to guess what you might need to render.
  • Uses destructuring similar to jsx render callback
  • Parent content to be rendered with child data is 'inline' with the template
  • You will probably never be able to inline a jsx function in your template (https://github.com/vuejs/vue/issues/7439)
Jsx vue slots

Closing Remarks

Why would I want to use the render prop pattern or JSX? The nice thing about this is that using the render function + JSX is a closer-to-the-compiler alternative and allows fine-grain control over rendering. You won't be able to use custom directives like v-model or v-if. Render props themselves have a lot of benefits, as outlined in this episode of Full stack radio where Adam interviews Kent C. Dodds.

If you're a Vue user, does this type of component composing surprise you? If so, I recommend going and reading the official docs which actually explain JSX and render functions in greater detail.

I love that we can share design principles between frameworks. It gives me warm fuzzy feelings in a cruel, cold world that believes there is a war on frameworks. In 2018, try and find the common ground.

If you enjoyed reading this, follow me on twitter where my DM's are always open!

Further reading:

  • Source code: https://github.com/darrenjennings/vue-jsx-render-props-example
  • Official Vue documentation: https://vuejs.org/v2/guide/render-function.html#Basics
  • Original article on using render props and what this article's title is referencing: https://cdb.Reacttraining.com/use-a-render-prop-50de598f11ce
  • A helpful article on similarities in frameworks converging React + Vue + Angular: http://varun.ca/convergence/

Props and $emit

When using Vue to develop a project, we divide the content of the project into modules, but sometimes there is data interaction between modules. In real project development, father-son and brother components need to pass values to each other. The most traditional way to pass values is props and $emit.

I. Props

Vue v-slot jsx

Prop is some custom features that you can register on components. When a value is passed to a prop feature, it becomes an attribute of that component instance. To pass a title to the blog component, we can include it in the list of acceptable props for the component with a props option.

1. Examples of props passing values

Vue Scoped Slots Jsx

Different parameters can also be passed to subcomponents:

2. Pros type validation
If we want each prop to have a specified value type and list prop as an object, the names and values of these properties are prop's respective names and types.

To make passing values more flexible, vue provides the following props authentication methods:

If a requirement is not met, Vue will warn you in the browser console. This is especially helpful in developing a component that will be used by others.

Note:

  • All props make a single downlink binding between their father and son props: updates to the parent prop flow downward to the child components, but not vice versa. This prevents accidental changes in the state of the parent component from the child component, resulting in incomprehensible data flow to your application.
  • Note that those props are validated before a component instance is created, so the properties of the instance (such as data, computed, etc.) are not available in default or validator functions.
  • Because components cannot always predict the parameters that other components will pass in when they call the current component, vue also allows components to pass in some non-props features when they are called. These features are automatically added to the root element of the component.

2. $emit

A child component is called by a parent component. When a child component triggers a function, it needs a parent component response, using $emit.

1. $emit simple example

We can also throw some data to the outside world when we throw an event.

If a component throws more than one data when throwing an event, it can continue to pass a value to $emit in the form of a parameter list, and then call it in the form of a parameter list in the parent component. But when there is a lot of data, it makes the code seem lengthy, so we recommend that all the data to be thrown be integrated into one object and passed in an object to the second parameter of the $emit function.

Slot slot slot

Slot is the second way that components are called, which improves the reusability of components.

When the child component calls the parent component and transfers its value, it tends to transfer in the data layer, but sometimes we hope that the child component can respond better to one of its parent components in the structure rendering layer, and the content of the child component can be rendered through the data control of the parent component.

If we need an operation result prompt box, the title, picture and button bar in the bullet box all render the concrete result according to the operation result. Using props or $emit can also achieve this effect, but if the results of multiple rendering are very different, then the code redundancy goes up again, so Vue provides a more concise way, that is, slots.

A slot is equivalent to encapsulating a component into a large framework. As for what and how to display it, it can transfer data when invoked, control it by data, and display the incoming content when invoked.

1. Small examples of slots

Note:
If the Alert component does not contain a < slot > element, anything between the start tag and the end tag will be discarded when the component is called.

2. Setting up backup slots for components

If a slot is reserved in a component, but the content is not distributed when the component is called, it may lead to some unpredictable errors in structure and logic, so sometimes it is necessary to set a default content for the slot.

3. Named sockets

To encapsulate a component with high reusability, a slot may not be enough. We can reserve multiple slots for each slot at different locations of the component structure, name each slot, and distribute the corresponding content to different slots when calling the component. This is the named slot.

Call the Alert component:

Abbreviation of Named Slot:

Note:

  • There is no < slot > with the name attribute set, and the default name value is default.
  • The v-slot attribute can only be added to one < template > (except for exclusive default slots).

4. Scope slots

Sometimes we need to access the data inside the component when we call it and distribute content to its socket. The data in the component can be bound to the slot prop, and then the data on the slot prop can be accessed at the same time when the component is called.

Call the slot and use the value of the slot prop:

Multiple slot prop s can be set for slots:

Vue v-slot jsx

Receive:

Slot prop can also be used for deconstruction:

Note:
If there are many slot props, it is recommended to integrate all data into one object and pass one slot prop.

Render function, JSX grammar and CreaeElement function

Render functions are the same as templates in creating html templates, but in some scenarios, the code implemented with templates is tedious and repetitive, so render functions can be used.

If render function is used in component rendering, then you can not use the < template > tag. Only < script > labels and < style > labels are required in component files.

Before we understand the render function, we need to define a concept of Vnode.

1. Vnode (virtual node)

When using Vue to develop a project, the structure rendered on the browser is rendered on the browser by Vue through various conditions, loops, calculations and other operations of the underlying mechanism. We regard the final result rendered on the browser as a real DOM tree.

But Vue responds to data efficiently. Faced with such efficient data response, it is also necessary to update nodes in the page equally efficiently. However, the structure of DOM is very large and complex, and it is particularly difficult to complete all DOM updates.

For example, we render a merchandise management list. When a certain value of a commodity changes, the list rendering of the page also needs to be updated. If we want to use native JS to render, we may need to re-render the entire table, or a row. If you want to locate a cell accurately, the code is very demanding.

Fortunately, when using Vue, we don't need to update the DOM tree manually using JS. Vue provides a virtual DOM tree through which it can track how it wants to change the real DOM.

DOM nodes written in vue file and DOM in render function are virtual DOM. When browser renders, all virtual DOM will be calculated and rendered on browser finally.

When we create a virtual DOM, we include all the information of the virtual DOM, such as child elements, class names, styles, locations, and so on.

Vue instances provide render functions to render virtual DOM, and render function parameters (also a function) to create virtual DOM.

2. Example render function

The < Home > component can be called normally, and the < div > rendered by the render function is taken when it is called.

render function:

  • The parameter is the ce function (which is written as createElement in many places).
  • The return value is a VNode (node to be rendered).

3. Parameter of render function - createElement function

The parameter of render function is the createElement function, which creates VNode as the return value of render.

The createElement function takes three parameters:

  • Parametric 1:
    String Object Function
    An HTML tag name, component option object, or resolve has one of the async functions mentioned above. Required items.
  • Parametric 2:
    Object
    An object that contains all the relevant attributes of this tag (or template). Optional.
  • Parametric 3:
    String Array
    A child node or list created by createElement.

Following are detailed descriptions and examples of the second and third parameters of createElement:

4. JSX grammar

If the structure in a template is relatively simple, we can use the createElement function, but once the structure is slightly more complex, the code becomes particularly lengthy.

If you want to continue using render functions, you need to use JSX grammar. Because JSX grammar allows HTML structures to be written in JS code.

Jsx Vue Slots

JSX grammar may be more widely used in React.

Vue V-slot Jsx

Added by flyersun on Thu, 01 Aug 2019 08:48:09 +0300