首頁  >  文章  >  web前端  >  vue render開發實例詳解

vue render開發實例詳解

php中世界最好的语言
php中世界最好的语言原創
2018-04-28 13:51:351888瀏覽

這次帶給大家vue render開發實例詳解,vue render開發的注意事項有哪些,下面就是實戰案例,一起來看一下。

簡介

在使用Vue進行開發的時候,大多數情況下都是使用template進行開發,使用template簡單、方便、快捷,可是有時候需要特殊的場景使用template就不是很適合。因此為了很好使用render函數,我決定深入窺探。各位看官如果覺得下面寫的有不正確之處還望看官指出,你們與我的互動就是寫作的最大動力。

場景

官網描述的場景當我們開始寫一個透過level prop 動態產生heading 標籤的元件,你可能很快就會想到這樣實作:

<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>
Vue.component('anchored-heading', {
 template: '#anchored-heading-template',
 props: {
  level: {
   type: Number,
   required: true
  }
 }
})

在這種場景中使用template 並不是最好的選擇:首先程式碼冗長,為了在不同層級的標題中插入錨點元素,我們需要重複地使用< /slot>。

雖然模板在大多數元件中都非常好用,但是在這裡它就不是很簡潔的了。那麼,我們來嘗試使用 render 函數重寫上面的範例:

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

簡單清晰很多!簡單來說,這樣程式碼精簡很多,但需要非常熟悉 Vue 的實例屬性。在這個例子中,你需要知道當你不使用 slot 屬性向元件傳遞內容時,例如 anchored-heading 中的 Hello world!,這些子元素被儲存在元件實例中的 $slots.default中。

createElement參數介紹

接下來你需要熟悉的是如何在 createElement 函數中產生範本。這裡是createElement 接受的參數:

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

深入data 物件

有一件事要注意:正如在範本語法中,v-bind:class 和v-bind :style ,會特別被對待一樣,在VNode 資料物件中,下列屬性名稱是等級最高的欄位。這個物件也允許你綁定普通的 HTML 特性,就像 DOM 屬性一樣,例如 innerHTML (這會取代 v-html 指令)。

{
 // 和`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'
}

條件渲染

既然熟讀以上api接下來咱們就來點實戰。

之前這樣寫

//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
  }
});

render這樣寫

//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
  }
});

列表渲染

之前是這樣寫的,而且v-for 時template內必須被一個標籤包裹

//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
    }]
  }
});

#render這樣寫

//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
    }]
  }
});

v-model

之前的寫法

//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: '', 
  }
});

render這樣寫

//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: '', 
  }
});

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

angular實作頁面局部列印步驟詳解

vue常用元件使用詳解

以上是vue render開發實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn