Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue render函数 #13

Open
Wscats opened this issue Mar 8, 2017 · 0 comments
Open

vue render函数 #13

Wscats opened this issue Mar 8, 2017 · 0 comments

Comments

@Wscats
Copy link
Owner

Wscats commented Mar 8, 2017

createElement的函数格式,注意只能拥有一个根节点(VNode)

// @returns {VNode}
createElement(
  // {String | Object | Function}
  // 一个 HTML 标签,组件选项,或一个函数
  // 必须 Return 上述其中一个
  'div',
  // {Object}
  // 一个对应属性的数据对象
  // 您可以在 template 中使用.可选项.
  {
    // (该节点的属性值)
  },
  // {String | Array}
  // 子节点(VNodes). 可选项.
  [
    createElement('h1', 'hello world'),
    createElement(MyComponent, {
      props: {
        someProp: 'foo'
      }
    }),
    'bar'
  ]
)

视图层

<div id="app">
</div>

image

new Vue({
	el: '#app',
	render: function(createElement) {
		let a = 1;
		return createElement('div', {
			style: {
				color: 'red',
				fontSize: '14px'
			}
                        //注意class是關鍵詞
			'class': {
				foo: true,
				bar: false
			}
		}, [
			createElement('h' + a, 'render函數'),
			createElement('p', {
				style: {
					color: 'blue',
					fontSize: '12px'
				}
			}, [
				createElement('span', 'Hello Wscats'), '!'
			]),
		])
	}
})

20 个重复的段落
image

new Vue({
	el: '#app',
	render: function(createElement) {
		return createElement('div',
			Array.apply(null, {
				length: 20
			}).map(function() {
				return createElement('p', 'hi')
			})
		)
	}
})

image

let abc = Vue.extend({
	template:"<p>wscats</p>"
})
//or// let cba = require('./app/cba.vue')
new Vue({
	el: '#app',
	render: function(createElement) {
		return createElement(abc)
	}
})

image

new Vue({
	el: '#app',
	render: function(createElement) {
		return createElement('h1', 'hello world')
	},
})
new Vue({
	el: '#app',
	data: {
		items:[{
			name:'wscat'
		},{
			name:'autumn'
		},{
			name:'eno'
		}]
	},
	render: function(createElement) {
		if(this.items.length) {
			return createElement('ul', this.items.map(function(item) {
				return createElement('li', item.name)
			}))
		} else {
			return createElement('p', 'No items found.')
		}
	}
})

等同于

<ul v-if="items.length">
  <li v-for="item in items">{{ item.name }}</li>
</ul>
<p v-else>No items found.</p>

更多详情可参考官方文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant