如何使用Vuejs实现带样式的单文件组件

这篇文章将为大家详细讲解有关如何使用Vuejs实现带样式的单文件组件,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

Vuejs实现单文件组件的方法,具体内容如下

代码如下:

example.html

<script src="vue.js"></script>
<div id="example">
 <h4>Vue component<h4>
 <counter></counter>
 <counter></counter>
</div>
//引入组件mycomp.js
<script src="mycomp.js"></script>
<script>
new Vue({
  el: '#example'
})
</script>

mycomp.js

//heredoc方法输出注释中的组件代码
function heredoc(fn){
  return fn.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
}
//输出组件代码
document.write(heredoc(function(){
/*
<style>
.my {color:red;padding:10px;}
</style>

<script type="text/x-template" id="c">
<p class="my" v-on:click="todo+=1">
 {{todo}}
</p>
</script>

<script>
Vue.component('counter',{
 template: "#c",
 data: function () {
  return {
    todo: 1
  }
 }
})
</script>
*/}))

运行结果:

如何使用Vuejs实现带样式的单文件组件

以简单的js文件形式实现了Vue单文件组件, 优点是带样式, 用法简单, 接近于.vue文件,

不用webpack, 不用发ajax请求, 直接引入使用 !

关于“如何使用Vuejs实现带样式的单文件组件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。