背景

相信大家在使用Vue开发项目时,基本都是以单文件组件的形式开发组件的,这种方式好处多多:

1.代码集中,便于开发、管理和维护

2.可复用性高,直接将vue文件拷贝到新项目中

我暂时就想到这两点,童鞋们可以在评论里帮我补充;因为有这么多优点,所以决定有必要将vue组件的常用配置项提炼出来,形成一个组件模板,方便日后项目开发复用

1<template>2<div>3<h2>`title`</h2>4<ChildComponents></ChildComponents>5</div>6</template>7<script>8//子组件要提前引入,才可使用9importChildComponentsfrom'./ChildComponents.vue'10//也可引入一些公共Js脚本或类库11importCookiefrom'../lib/cookie.js'1213//Js部分尽量采用ES6语法,webpackbabel插件会转义兼容14exportdefault{15//组件私有数据(必须是function,而且要return对象类型)16data(){17return{18title:'组件标题',19firstName:'',20lastName:'',21}22},23//父组件传递过来的数据(两种方式声明:1.数组2.对象)24//数组方式25props:['age'],26//对象方式27/*props:{28age:{29type:Number,30default:0,31required:true,32validator:function(value){33returnvalue>=034}35}36}*/37//计算属性38computed:{39fullName(){40returnthis.firstName+this.lastName41}42},43//监听44watch:{45title(preVal,newVal){46console.log(`改变之前的值:${preVal};改变之后的值:${newVal}`)47}48},49//函数集,自己封装,便于开发使用50methods:{51getCurrentDate(){52returnnewDate().toLocaleDateString()53}54},55//生命周期钩子:实例初始化之后,数据观测(dataobserver)和event/watcher事件配置之前被调用56beforeCreated(){57console.log('componentbeforecreated')58},59//生命周期钩子:组件实例完成创建之后调用60created(){61console.log('componentcreated')62},63//生命周期钩子:组件实例渲染完成时调用64mounted(){65console.log('componentmounted')66},67//要用到哪些子组件(如果组件已是最小粒度,那么可省略该属性)68components:{69ChildComponents70}71}72</script>73<stylelang="scss"scoped>74/**使用scss编写样式,既可提高开发效率,也方便维护75*scoped省略后,该样式片段会应用到页面全局76*支持import语法引入css文件77*/78@import"../base/reset.css";79div{80h2{81color:#c23a3f;82}83}8485</style>