This is the 12th day of my participation in Gwen Challenge
Hi, I’m Daotin, front end team leader. If you want to get more front end highlights, follow me and unlock new front end growth poses.
The following text:
Why use the Render function instead of the template template?
Vue recommends using templates to create your HTML in most cases. However, in some scenarios, you really need the full programming power of JavaScript. In this case you can use render functions, which are closer to the compiler than templates.
Since vue is a virtual DOM, it also needs to be translated into a VNode function when it gets the template. Using the render function to build the DOM, Vue avoids the translation process.
Use the template syntax and the render function to render a different title format depending on the level (H1-H6) page passed in.
In the child component it looks like this:
// Child component child1.vue<template>
<div>
<h1 v-if="level == 1">
<slot></slot>
</h1>
<h2 v-if="level == 2">
<slot></slot>
</h2>
<h3 v-if="level == 3">
<slot></slot>
</h3>
<h4 v-if="level == 4">
<slot></slot>
</h4>
<h5 v-if="level == 5">
<slot></slot>
</h5>
<h6 v-if="level == 6">
<slot></slot>
</h6>
</div>
</template>
<script>
export default {
props: {
level: {
require: true.type: Number}}};</script>
Copy the code
The parent component then calls:
<anchored-heading :level="1">Hello world!</anchored-heading>
Copy the code
Look at the render implementation:
<script>
export default {
props: {
level: {
require: true.type: Number,}},render(createElement) {
return createElement('h' + this.level, this.$slots.default); }};</script>
Copy the code
Comparing the two implementations, we found that using a template was not the best choice, not only was the code verbose, but it was written repeatedly in headings at every level. Using the Render function implementation looks much simpler, which makes the code much simpler, but requires familiarity with Vue instance properties (the default property includes all nodes that are not included in named slots, or v-slot:default). .
Render function
The render function is a function that returns vNodes (virtual nodes).
CreateElement is the argument to the Render function, which is itself a function, and has three arguments. The next point describes these three parameters.
The CreateElement function is also conventionally written as h.
The first parameter (must) : {String | Object | Function}
String
, represents the name of the HTML tag, such asdiv
Object
, a component option object that contains dataFunction
, returns an async function that contains the label name or component option object
render: function (createElement) {
// String
return createElement('h1');
//Object
return createElement({
template:
Dao Tingtu said
})
// Function
let domFun = function () {
return {
template:
Dao Tingtu said
}}return createElement(domFun())
}
Copy the code
Second argument (optional) – {Object}
Attributes in a template with the corresponding data objects The commonly used have class | style | attrs | domProps | on
- Class: indicates the name of the control class
- Style: the style
- Attrs: Used to write normal HTML attributes such as id SRC
- DomProps: For writing native DOM properties
- On: : used to write native methods
return createElement('div', {
// Same API as' v-bind:class '
'class': {
foo: true.bar: false
},
// Same API as' v-bind:style '
style: {
color: 'red'.fontSize: '14px'
},
// Normal HTML features
attrs: {
id: 'foo'
},
/ / component props
props: {
myProp: 'bar'
},
/ / DOM attributes
domProps: {
innerHTML: 'baz'
},
// Event listener based on" on"
// So modifiers such as V-on :keyup.enter are no longer supported
// You need to manually match keyCode.
on: {
click: this.clickHandler
},
// For components only, this is used to listen for native events, not for components using vM. $emit emitted events.
nativeOn: {
click: this.nativeClickHandler
},
// Custom instruction. Note: You cannot set a value to a bound old value
// Vue will keep on tracking you
directives: [{name: 'my-custom-directive'.value: '2'
expression: '1 + 1'.arg: 'foo'.modifiers: {
bar: true}}].// Scoped slots in the form of
// { name: props => VNode | Array<VNode> }
scopedSlots: {
default: props= > h('span', props.text)
},
// If the child component has a name that defines slot
slot: 'name-of-slot'
// Other special top-level attributes
key: 'myKey'.ref: 'myRef'
})
Copy the code
The third parameter (optional) – {String | Array}
VNodes, constructed from createElement(), normally receives a string or an array
return createElement('div', {
/ /...
}, [
createElement('h1'.'I'm H1 heading'),
createElement('h6'.'I'm H6 title')])Copy the code
Event modifier
on: {
'! click': this.doThisInCapturingMode,
'~keyup': this.doThisOnce,
'~! mouseover': this.doThisOnceInCapturingMode
}
Copy the code
Template event modifier | Render = render |
---|---|
.passive |
& |
.capture |
! |
.once |
~ |
. The capture. Once or once. The capture |
~! |
JSX configuration and usage in Render
Some of these createElements can be quite tricky to write, especially if you have nested tags. We can use JSX syntax to make it easier to write the render function, but we need a bit of configuration before we write it.
configuration
- Install VUE’s JSX dependencies
npm install\
babel-plugin-syntax-jsx\
babel-plugin-transform-vue-jsx\
babel-helper-vue-jsx-merge-props\
babel-preset-env\
--save-dev
Copy the code
- After the installation is complete, the
.babelrc
Configuration file"plugins": ["transform-vue-jsx"]
.
{
"presets": ["env"],
"plugins": ["transform-vue-jsx"]
}
Copy the code
This plugin allows you to:
<div id="foo">{this.text}</div>
Copy the code
Convert to the following form:
h('div', {
attrs: {
id: 'foo'}},this.text])
Copy the code
Change the JS parsing part of the Webpack configuration file to test: /.jsx? $/ indicates that the JSX code block is parsed.
use
Before switching to JSX we wrote:
createElement(
'anchored-heading', {
props: {
level: 1
}
}, [
createElement('span'.'Hello'),
' world! '])Copy the code
After changing to JSX, our render function could be written like this:
import AnchoredHeading from './AnchoredHeading.vue'
new Vue({
el: '#demo',
render (h) {
return (
<AnchoredHeading level={1}>
<span>Hello</span> world!
</AnchoredHeading>)}})Copy the code
Matters needing attention
Note: the h function is short for the Vue instance’s $createElement method, which must be in the scope of JSX. Since this method is passed to the component rendering function as the first argument, in most cases you would do this:
Vue.component('jsx-example', {
render (h) { // <-- h must be in scope
return <div id="foo">bar</div>}})Copy the code
However, starting with version 3.4.0, const h = this.$createElement is automatically injected into each method so that you can remove the (h) argument.
Reference documentation
- Juejin. Cn/post / 684490…
- Github.com/vuejs/babel…
Recent hot articles:
- Waterfall flow, it’s so easy
- Four common ajax cross-domain solutions (easy to understand)
- Vue. Js Naming Style Guide (Easy to remember Version)
Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin, Daotin