Vue的几个小坑&子选择器&测试相关
1. vue中html属性使用简写的问题
假如子组件props进行类型检测,那么子组件接收不到
//parent
<g-button right>BTN</button>
//component-A
props:['right']
mount(){
console.log(this.right) //undefined
}
当子组件props进行类型检测,子组件能接受到值.
//parent
<g-button right>BTN</button>
//component-B
props:{
right:{
type: Boolean,
default: false,
}
}
mount(){
console.log(this.right) // true
}
2. 组件点击事件失效的问题
点击button元素,事件不生效.
//parent
<g-button @click="loading = !loading">BTN</button>
解决办法.
- 父元素事件绑定中添加修饰符native.
//parent
<g-button @click.native="loading = !loading">BTN</button>
- 子组件中监听自身的click事件,调用函数给父组件发送click事件,父组件监听该click事件.
//parent
<g-button @click="loading = !loading">BTN</button>
//component
<button @click="_click">
<slot></slot>
</button>
methods:{
_click(){
this.$emit('click')
}
}
3. scss子选择器
注意:子选择器写在子元素上,而不是父元素上
错误:
//false
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
ul{
&:first-child{
color:red
}
}
正确:
//true
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
ul{
li{
&:first-child{
color:red
}
}
}
- 几个有用子选择器
//第一个元素
li:first-child
//最后一个元素
li:last-child
//非第一个元素
li:not(:first-child)
4. 测试相关
- BDD 行为驱动开发 (用自然语言描述)
- TDD 测试驱动开发 (通过测试)
- Assert 断言 (主观认为,例如console.log)
库 chai.js
Should 应该
Expect 期望
Assert 断言
安装
npm -D chai
使用
import chai from 'chai'
const { expect } = chai
let test = 'abc'
expect(test).to.eq('abc')
mock
chai-spies
监听函数
使用:
//引入
import chai from 'chai'
import spies from 'chai-spies'
chai.use(spies)
const { expect } = chai
//vue使用
const Constructor = Vue.extend(gButton);
const vm = new Constructor({
propsData: {
icon: 'setting',
}
})
vm.$mount();
let spy = chai.spy(function () { })
vm.$on('click', spy)
let button = vm.$el
button.click();
expect(spy).to.have.been.called()
版权声明:本博客所有文章除特殊声明外,均采用 CC BY-NC 4.0 许可协议。转载请注明出处 Roxas Deng的博客!