Vue2.0 Jsx

Posted on  by admin

JSX 是一种 Javascript 的语法扩展,JSX = Javascript + XML,即在 Javascript 里面写 XML,因为 JSX 的这个特性,所以他即具备了 Javascript 的灵活性,同时又兼具 html 的语义化和直观性. 有时候,我们使用渲染函数(render function)来抽象组件,渲染函数不是很清楚的参见官方文档, 而渲染函数有时候写起来是非常痛苦的. 这显然是吃力不讨好的,这个时候就派上 JSX 上场了。在 Vue 中使用 JSX,需要使用 Babel插件,它可以让我们回到更接近于模板的语法上,接下来就让我们一起开始在 Vue 中写 JSX 吧.

指令

快读创建一个 Vue 项目,直接使用 vue-cli 创建一个项目:. 这里展示在 Vue 中书写一些基础内容,包括纯文本、动态内容、标签使用、自定义组件的使用,这些跟我们平时使用单文件组件类似,如下所示:.

  • Attributes 的绑定跟普通的 HTML 结构一样. 注意,如果动态属性,之前是 v-bind:placeholder="this.placeholderText" 变成了placeholder={this.placeholderText}.
  • 像 input 标签,就可以如下批量绑定属性. 具名插槽:父组件的写法和单文件组件模板的类似,通过 slot="header" 这样方式指定要插入的位置。子组件通过 this.$slots.header 方式指定插槽的名称,其中 header 就是插槽的名称.
  • 作用域插槽:子组件中通过 {this.$scopedSlots.test({ user: this.user })} 指定插槽的名称是 test,并将 user 传递给父组件。父组件在书写子组件标签的时候,通过 scopedSlots 值指定插入的位置是 test,并在回调函数获取到子组件传入的 user 值.

总结

函数式组件

函数式组件是一个无状态、无实例的组件,详见官网说明,新建一个 FunctionalComponent.js 文件,内容如下:. 本文主要介绍了为什么要在 Vue 中使用 JSX,以及如何在 Vue 中使用 JSX. Vue 2.0 vnode system is really nice, and now that typescript are part of the npm packages, the natural next step is trying to use the TSX format (would be so nice as a replacement for vue files), but I simply can’t find the proper prototype for render and how to setup tsconfig.json etc.

I found the vue-ts-loader, but no hint as to how to use tsx files.

基础内容

tsc has two jsx modes, the “react” mode and the “preserve”, will be be able to use the direct react method, or do vi need to chain it in webpack via the std jsx parser ?

The createElement method takes in three arguments:

  • A render element, which can be an HTML tag name or a component
  • An object that can contain data objects such as attributes, props, DOM props, styles, classes, and event handlers
  • A child argument that can either be an array of children nodes, a single child node or plain text

The createElement parameter in render functions is often written as h to denote Hyperscript as explained by Evan You — the creator of Vue.

Hyperscript stands for the script that generates HTML structures and helps create markups with JavaScript. The render function above can be rewritten like this:

参考

According to Evan You:

The Virtual DOM is a lightweight representation of what the actual DOM should look like at a given point in time

Vue creates a Virtual DOM that keeps track of all the changes made to the real DOM and on every data change Vue returns a new Virtual DOM, it then compares the old virtual DOM to the new one and checks for specific changes and makes adjustments in the real DOM.

The process of comparing and checking changes between the old and the new Virtual DOM is referred to as diffing.

This mini-app helps explore the Vue templates and render functions, you can learn more about render functions in Vue and the Virtual DOM here.

为什么要在 Vue 中使用 JSX

JSX is an XML-like syntax extension for writing JavaScript. It’s a syntactic abstraction of render functions. It was built by Facebook’s engineering team and originally intended to be used in building React apps in a more concise and elegant way.

JSX, similar to Vue templates, get compiled to render functions under the hood at build time.

JSX 是什么

  • It makes no assumption about how your code should look or be processed. There is no defined way to write JSX
  • JSX helps prevent cross-site scripting attacks because you can never inject code that is not explicitly written in your application, everything is converted to a string before being rendered
  • JSX is dynamic. It gives you the power to do whatever you want to as it gives access to the full programmatic powers of JavaScript
  • There is no registration of imported components, you can make use of them on the go
  • It couples logic and markup together, you don’t have to write markup separately from the JavaScript
  • Several components can be written in a single file as opposed to templates where you have to write every component in separate files
  • JSX gives access to the spread operator, it makes things, like passing an object as props, easier

开始

Attributes/Props

Template implementation

The block of code above displays a user’s name if the user’s age is greater than 18.

JSX implementation

In JSX, the condition to check for a user’s age is wrapped in a function housed inside the Vue method instance and then the function is invoked in the render method.

插槽

Template implementation

The v-for directive executes a block of code a number of times. In the code above we use the v-for directive to render a list of items in an array.

JSX implementation

In JSX, the items in an array can be mapped over, using the ES2015 .map() method.

Events(v-on)

Template implementation

The v-on directive listens to DOM events and triggers a function that performs a defined operation. In the code shown above, a click of the button triggers the handleButtonClick() function which displays an alert() dialog box.

JSX implementation

Interpolation (v-html)

Template implementation

v-html is used to set elements innerHTML, the code above sets the innerHTML of the div to the content of rawHtml.

JSX implementation

domPropsInnerHTML attribute performs the same task as v-html , it sets the content of the div to rawHtml.

Importing components

Template implementation

JSX implementation

When using JSX there’s no need to register a component after importing it, you can just use it directly.

How to set up a Vue project with JSX

For this section, we will be building a trivial app that displays a little bit of information about selected countries.

Create a new project

Install the dependencies needed to make use of JSX in your project using yarn:

Configure your babel file to use the presets for JSX by including the following in your .babelrc or babel.config.js file, located in your project root directory:

The @vue/babel-preset-jsx preset enables you to use the JSX presets made available by the Vue team.

Vue automatically injects h which is short for createElement in every method, so you don’t have to always declare h as a parameter in your render() function.

Testing out our Vue-JSX app

To test it out, replace the content of your HelloWorld.vue file in src/components folder with the following:

You should get a result similar to this:

Conclusion

We’ve seen how render functions work and how to set up a Vue project to use JSX, check out the repository to this article on GitHub. To learn about more awesome things you can do with Vue.js, check out the documentation.

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - Start monitoring for free.