web-runtime-with-compiler.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import config from 'core/config'
  2. import { warn, cached } from 'core/util/index'
  3. import { query } from 'web/util/index'
  4. import Vue from './web-runtime'
  5. import { compile } from './web-compiler'
  6. const idToTemplate = cached(id => query(id).innerHTML)
  7. const cache1 = Object.create(null)
  8. const cache2 = Object.create(null)
  9. function createRenderFns (template) {
  10. const preserveWhitespace = config.preserveWhitespace
  11. const cache = preserveWhitespace ? cache1 : cache2
  12. if (cache[template]) {
  13. return cache[template]
  14. }
  15. const res = {}
  16. const compiled = compile(template, { preserveWhitespace })
  17. res.render = new Function(compiled.render)
  18. const l = compiled.staticRenderFns.length
  19. if (l) {
  20. res.staticRenderFns = new Array(l)
  21. for (let i = 0; i < l; i++) {
  22. res.staticRenderFns[i] = new Function(compiled.staticRenderFns[i])
  23. }
  24. }
  25. return (cache[template] = res)
  26. }
  27. const mount = Vue.prototype.$mount
  28. Vue.prototype.$mount = function (el) {
  29. el = el && query(el)
  30. const options = this.$options
  31. // resolve template/el and convert to render function
  32. if (!options.render) {
  33. let template = options.template
  34. if (template) {
  35. if (typeof template === 'string') {
  36. if (template.charAt(0) === '#') {
  37. template = idToTemplate(template)
  38. }
  39. } else if (template.nodeType) {
  40. template = template.innerHTML
  41. } else {
  42. warn('invalid template option:' + template, this)
  43. }
  44. } else if (el) {
  45. template = getOuterHTML(el)
  46. }
  47. if (template) {
  48. const { render, staticRenderFns } = createRenderFns(template)
  49. options.render = render
  50. options.staticRenderFns = staticRenderFns
  51. }
  52. }
  53. mount.call(this, el)
  54. }
  55. /**
  56. * Get outerHTML of elements, taking care
  57. * of SVG elements in IE as well.
  58. *
  59. * @param {Element} el
  60. * @return {String}
  61. */
  62. function getOuterHTML (el) {
  63. if (el.outerHTML) {
  64. return el.outerHTML
  65. } else {
  66. var container = document.createElement('div')
  67. container.appendChild(el.cloneNode(true))
  68. return container.innerHTML
  69. }
  70. }
  71. Vue.compile = compile
  72. export default Vue