原創: Vuejs實現單文件組件新方法,帶樣式


代碼如下:

example.html

復制代碼
 1 <script src="vue.js"></script>  2 <div id="example">  3 <h3>Vue component<h3>  4 <counter></counter>  5 <counter></counter>  6 </div>  7 <!--引入組件mycomp.js-->  8 <script src="mycomp.js"></script>  9 <script> 10 new Vue({ 11  el: '#example' 12 }) 13 </script>
復制代碼

mycomp.js

復制代碼
 1 //heredoc方法輸出注釋中的組件代碼  2 function heredoc(fn){  3 return fn.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];  4 }  5 //輸出組件代碼  6 document.write(heredoc(function(){  7 /*  8 <style>  9 .my {color:red;padding:10px;} 10 </style> 11 12 <script type="text/x-template" id="c"> 13 <p class="my" v-on:click="todo+=1"> 14  {{todo}} 15 </p> 16 </script> 17 18 <script> 19 Vue.component('counter',{ 20  template: "#c", 21  data: function () { 22  return { 23  todo: 1 24  } 25  } 26 }) 27 </script> 28 */}))
復制代碼

運行結果:

以簡單的js文件形式實現了Vue單文件組件, 優點是帶樣式, 用法簡單, 接近於.vue文件,

不用webpack, 不用發ajax請求, 直接引入使用 !


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM