表单开发确定是平常开发中必不可少的环节,但是设计图常常会有表单默认值的设计,好比:css
需求方的需求点是:在没有输入值的时候显示默认值,在输入值的时候显示输入值。vue
一般就能想到用placeholder
来解决这个问题,而且一般会用v-model
来绑定data
中的值。而后,data
的值再设定默认值为空sass
//script data(){ return { index:0, name:'' } } //template <input type="number" placeholder="默认值index" v-model="index"/> <input type="text" placeholder="默认值name" v-model="name"/>
以上这种效果是,第一个input的placeholder的值显示不出,显示了index的值:0,不符合需求
第二种能显示placeholder的值,需求知足。app
可是一些复杂的需求,好比,让用户选择城市名(city)和国家名(country),最后在一个变量(countryAndCity)上显示,这个时候就要用computed
less
//template <input type="text" placeholder="城市" v-model="city"/> <input type="text" placeholder="国家" v-model="country"/> <input type="text" placeholder="国家+城市" v-model="countryAndCity"/> //script data(){ return { city:'', country:'' } }, computed:{ countryAndCity () { let str = '' if(this.city && this.country){ str = `${this.city}+${this.country}` } return str } }
在上面就须要作个判断,当city和country有值的状况才显示结果,不然显示placeholder的值。异步
诸如通过设计师设计的单选和多选按钮组件化
单选按钮就比较简单了post
//template <li v-for="item, index in list" :class="{"active":currentIndex === index}" @click="select(index)">{{item}}</li> //script data(){ return { currentIndex:0, list:['aa','bb','cc','dd'] } }, methods:{ select(index){ this.currentIndex = index } }
上面很简单,大概看看就懂了,这是单选的状况,那要是多选的状况呢,那就要换个思路了this
首先换个数据格式spa
data(){ return { list:[ {text:'aa',isActive:false}, {text:'bb',isActive:false} {text:'cc',isActive:false}' ] } }, methods:{ select(index){ this.list[index].isActive = !this.list[index].isActive } }
而后template就要变成这样
<li v-for="(item, index) in list" :class="{"active":item.isActive}" @click="select(index)">{{item.text}}</li>
动态组件通常不多用到,可是要作动态引入组件的时候真的超级好用。以前作过的组件配置系统核心就是它。我用的是一个动态组件循环,而后用is获取组件名,用props获取各个组件的自定义props
<components :is="item.name" v-for="item, index in componentList" :props="item.props"></components> componentList:[{ name:'index',props:{title:'title'}}]
created和mounted在客户端渲染时期window对象都是存在的,因此能够直接操做。
可是在服务端渲染时期,它们二者的window都是不存在的,因此要加一句判断,在全部逻辑前面
if(typeof window !== 'object') return ;
基于组件化思惟,不少时候咱们会把一个页面拆分红几个组件,而后会提取一些公用的组件,好比dialog弹窗组件,他的打开和关闭,都是根据引用组件页面的data的一个值来决定,
//app.vue <dialog v-if="isDialog"></dialog> data(){ return { isDialog:false } } methods:{ showDialog(){ this.isDialog = true } }
可是关闭按钮一般是写在dialog组件内部的,也就是说,在引用组件页面是没有这个按钮能够点击的,
因此,能够在dialog里面将点击时间的信号传递出来,引用组件页面接收到了信号,再控制关闭
//dialog.vue <div @click="close"> 点击关闭 </div> methods:{ close() { this.$emit('close') } } //app.vue <dialog v-if="isDialog" @close="closeDialog"></dialog> data(){ return { isDialog:false } } methods:{ showDialog(){ this.isDialog = true }, closeDialog(){ this.isDialog = false } }
大体的思路就是把真正关闭的操做,放在isDialog
的页面,方便操做。
后续还会出一个不这样引用,直接在methods的方法中引用的公用组件写法,敬请期待
vue中的css能够用scoped这个关键子来限制css的做用域
<style scoped>...</style>
这个平常就会用到,由于这样就不用考虑class的命名会重合,加上使用sass、less、stylus、postcss等css处理器,效果简直杠杠的。
可是若是你想改动到body这个元素的css样式,可是又不想改动公用layout模板。那你就能够在一个vue文件写两个style
标签
<style> body{...} </style> <style scoped> .. .</style>
大概就先写这么多啦,以后再补充,欢迎关注