webpack 打包不会玩,整了这么个小玩具
一段 vue 绑定代码,关键点在 gmallComponent
1、异步加载外部 vue 文件(非 .vue)
2、按一定规则拆分 template、script、style
new Vue({ el: '#app_vuejs_replace', data: { search_key : '', results : [], pageindex : 1, selecteditem : null }, components: { 'vue-test': gmallComponent('gz/test.html', { props: ['items'] }) } });
gz/test.html 使用习惯几乎遵循 vue 原生,定义模板、脚本、样式
<div> <div>I am async!</div> <div v-for="item in items" @click="onclick(item.company_name)"> {{item.web_title}} </div> </div> <script> export = { methods: { onclick: function(msg) { showTip(msg); } } } </script> <style> .fade-enter-active, .fade-leave-active { transition: opacity .9s } .fade-enter, .fade-leave-active { opacity: 0 } </style>
将以下代码定义到公共 .js 文件中
<script type="text/javascript"> function gmallComponent(url, vuecom) { if (!vuecom) vuecom = {}; return function(resolve, reject) { $.get(url).done(function(r) { var rl = r.toLowerCase(); var style = ''; var styleIndexEnd = rl.lastIndexOf('</style>'); var styleIndex = rl.lastIndexOf('<style', styleIndexEnd); if (styleIndexEnd !== -1 && styleIndex !== -1) { style = r.substring(styleIndex, styleIndexEnd); style = style.substr(style.indexOf('>') + 1); style = '<component scoped :is="\'style\'">' + style + '</component>'; } var scriptIndexEnd = rl.lastIndexOf('<\/script>'); var scriptIndex = rl.lastIndexOf('<script', scriptIndexEnd); if (scriptIndexEnd !== -1 && scriptIndex !== -1) { var script = r.substring(scriptIndex, scriptIndexEnd); script = script.substr(script.indexOf('>') + 1); script = '(' + script.replace(/export\s*=\s*\{/i, '{') + ')'; var obj = eval(script); for (var a in obj) vuecom[a] = obj[a]; } var template = r.substring(0, Math.min(styleIndex, scriptIndex)); if (style) { var index = template.lastIndexOf('</'); if (index !== -1) template = template.substr(0, index) + style + template.substr(index); } vuecom.template = template; debugger resolve(vuecom); }); }; }
最新评论: