Home Web Front-end JS Tutorial Using Vue render from scratch

Using Vue render from scratch

Jun 08, 2018 pm 01:56 PM
render vue

This time I will bring you the use of Vue render from scratch. What are the precautions for using Vue render from scratch? The following is a practical case, let's take a look.

Introduction

When using Vue for development, in most cases, template is used for development. Using template is simple, convenient and fast, but sometimes it is necessary It is not very suitable to use template in special scenarios. So in order to make good use of the render function, I decided to take a closer look. If you feel that what is written below is incorrect, please point it out. Your interaction with me is the biggest motivation for writing.

Scenario

The scenario described on the official website When we start to write a component that dynamically generates a heading tag through level prop, you may quickly think of implementing it like this:

<script type="text/x-template" id="anchored-heading-template">
 <h1 v-if="level === 1">
  <slot></slot>
 </h1>
 <h2 v-else-if="level === 2">
  <slot></slot>
 </h2>
 <h3 v-else-if="level === 3">
  <slot></slot>
 </h3>
 <h4 v-else-if="level === 4">
  <slot></slot>
 </h4>
 <h5 v-else-if="level === 5">
  <slot></slot>
 </h5>
 <h6 v-else-if="level === 6">
  <slot></slot>
 </h6>
</script>
Copy after login
Vue.component('anchored-heading', {
 template: '#anchored-heading-template',
 props: {
  level: {
   type: Number,
   required: true
  }
 }
})
Copy after login

Using template in this scenario is not the best choice: first of all, the code is verbose, and in order to insert anchor elements in different levels of headers, we need to use repeatedly.

Although templates are very useful in most components, they are not very concise here. So, let’s try to rewrite the above example using the render function:

Vue.component('anchored-heading', {
 render: function (createElement) {
  return createElement(
   'h' + this.level,  // tag name 标签名称
   this.$slots.default // 子组件中的阵列
  )
 },
 props: {
  level: {
   type: Number,
   required: true
  }
 }
})
Copy after login

It’s much simpler and clearer! To put it simply, this code is much simpler, but it requires being very familiar with Vue's instance properties. In this example, you need to know that when you pass content to a component without using the slot attribute, such as Hello world! in anchored-heading, those child elements are stored in $slots.default in the component instance.

Introduction to createElement parameters

The next thing you need to be familiar with is how to generate a template in the createElement function. Here are the parameters accepted by createElement:

createElement(
 // {String | Object | Function}
 // 一个 HTML 标签字符串,组件选项对象,或者
 // 解析上述任何一种的一个 async 异步函数,必要参数。
 'p',
 // {Object}
 // 一个包含模板相关属性的数据对象
 // 这样,您可以在 template 中使用这些属性。可选参数。
 {
  // (详情见下一节)
 },
 // {String | Array}
 // 子节点 (VNodes),由 `createElement()` 构建而成,
 // 或使用字符串来生成“文本节点”。可选参数。
 [
  '先写一些文字',
  createElement('h1', '一则头条'),
  createElement(MyComponent, {
   props: {
    someProp: 'foobar'
   }
  })
 ]
)
Copy after login

Deep into the data object

One thing to note: as in the template syntax, v-bind:class and v-bind :style will be treated specially. In the VNode data object, the following attribute names are the highest-level fields. This object also allows you to bind normal HTML attributes, like DOM properties, such as innerHTML (this replaces the v-html directive).

{
 // 和`v-bind:class`一样的 API
 'class': {
  foo: true,
  bar: false
 },
 // 和`v-bind:style`一样的 API
 style: {
  color: 'red',
  fontSize: '14px'
 },
 // 正常的 HTML 特性
 attrs: {
  id: 'foo'
 },
 // 组件 props
 props: {
  myProp: 'bar'
 },
 // DOM 属性
 domProps: {
  innerHTML: 'baz'
 },
 // 事件监听器基于 `on`
 // 所以不再支持如 `v-on:keyup.enter` 修饰器
 // 需要手动匹配 keyCode。
 on: {
  click: this.clickHandler
 },
 // 仅对于组件,用于监听原生事件,而不是组件内部使用
 // `vm.$emit` 触发的事件。
 nativeOn: {
  click: this.nativeClickHandler
 },
 // 自定义指令。注意,你无法对 `binding` 中的 `oldValue`
 // 赋值,因为 Vue 已经自动为你进行了同步。
 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 => createElement('span', props.text)
 },
 // 如果组件是其他组件的子组件,需为插槽指定名称
 slot: 'name-of-slot',
 // 其他特殊顶层属性
 key: 'myKey',
 ref: 'myRef'
}
Copy after login

Conditional rendering

Now that we are familiar with the above API, let’s do some practical combat.

Write like this before

//HTML
<p id="app">
  <p v-if="isShow">我被你发现啦!!!</p>
</p>
<vv-isshow :show="isShow"></vv-isshow>
//js
//组件形式      
Vue.component('vv-isshow', {
  props:['show'],
  template:'<p v-if="show">我被你发现啦2!!!</p>',
});
var vm = new Vue({
  el: "#app",
  data: {
    isShow:true
  }
});
Copy after login

renderWrite like this

//HTML
<p id="app">
  <vv-isshow :show="isShow"><slot>我被你发现啦3!!!</slot></vv-isshow>
</p>
//js
//组件形式      
Vue.component('vv-isshow', {
  props:{
    show:{
      type: Boolean,
      default: true
    }
  },
  render:function(h){  
    if(this.show ) return h('p',this.$slots.default);
  },
});
var vm = new Vue({
  el: "#app",
  data: {
    isShow:true
  }
});
Copy after login

List rendering

It was written like this before, and when v-for, the template must be wrapped by a label

//HTML
<p id="app">
  <vv-aside v-bind:list="list"></vv-aside>
</p>
//js
//组件形式      
Vue.component('vv-aside', {
  props:['list'],
  methods:{
    handelClick(item){
      console.log(item);
    }
  },
  template:'<p>\
         <p v-for="item in list" @click="handelClick(item)" :class="{odd:item.odd}">{{item.txt}}</p>\
       </p>',
  //template:'<p v-for="item in list" @click="handelClick(item)" :class="{odd:item.odd}">{{item.txt}}</p>',错误     
});
var vm = new Vue({
  el: "#app",
  data: {
    list: [{
      id: 1,
      txt: 'javaScript',
      odd: true
    }, {
      id: 2,
      txt: 'Vue',
      odd: false
    }, {
      id: 3,
      txt: 'React',
      odd: true
    }]
  }
});
Copy after login

render is written like this

//HTML
<p id="app">
  <vv-aside v-bind:list="list"></vv-aside>
</p>
//js
//侧边栏
Vue.component('vv-aside', {
  render: function(h) {
    var _this = this,
      ayy = this.list.map((v) => {
        return h('p', {
          'class': {
            odd: v.odd
          },
          attrs: {
            title: v.txt
          },
          on: {
            click: function() {
              return _this.handelClick(v);
            }
          }
        }, v.txt);
      });
    return h('p', ayy);
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return this.list || [];
      }
    }
  },
  methods: {
    handelClick: function(item) {
      console.log(item, "item");
    }
  }
});
var vm = new Vue({
  el: "#app",
  data: {
    list: [{
      id: 1,
      txt: 'javaScript',
      odd: true
    }, {
      id: 2,
      txt: 'Vue',
      odd: false
    }, {
      id: 3,
      txt: 'React',
      odd: true
    }]
  }
});
Copy after login

v-model

Previous writing method

//HTML
<p id="app">
  <vv-models v-model="txt" :txt="txt"></vv-models>
</p>
//js
//input
Vue.component('vv-models', {
  props: ['txt'],
  template: '<p>\
         <p>看官你输入的是:{{txtcout}}</p>\
         <input v-model="txtcout" type="text" />\
       </p>',
  computed: {
    txtcout:{
      get(){
        return this.txt;
      },
      set(val){
        this.$emit('input', val);
      }
      
    }
  }
});
var vm = new Vue({
  el: "#app",
  data: {
    txt: '', 
  }
});
Copy after login

render is written like this

//HTML
<p id="app">
  <vv-models v-model="txt" :txt="txt"></vv-models>
</p>
//js
//input
Vue.component('vv-models', {
  props: {
    txt: {
      type: String,
      default: ''
    }
  },
  render: function(h) {
    var self=this;
    return h('p',[h('p','你猜我输入的是啥:'+this.txt),h('input',{
      on:{
        input(event){
          self.$emit('input', event.target.value);
        }
      }
    })] );
  },
});
var vm = new Vue({
  el: "#app",
  data: {
    txt: '', 
  }
});
Copy after login

Summary

Render function usage What's more, JavaScript's complete programming ability has an absolute advantage in performance. The editor is just analyzing it. As for the actual project, which method you choose for rendering still needs to be determined based on your project and actual conditions.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How json-server creates back-end data

Detailed explanation of the use of vuex state management

The above is the detailed content of Using Vue render from scratch. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

See all articles