在页面验证的时候,多数会使用 ref的使用,因为vue的生命周期的原因,需要 在this.$nextTick() 之后才能够正常的取到值。
在项目上使用的时候,ref绑定的是input,就使用value来判断验证是否该dom为空,其余div 和span等元素,使用innerHTML来判断。
例如
<div ref="content"></div>
<script>
// 在methos 里面的方法里写,为这里就省略了
const content = this.$refs.content;
if (content.innerHTML === ' ') {
returan false ; // 这里就写你需要的操作
}
</script>
以上是普通dom的使用;
$ref还可以用在子组件上,talk is cheap,show code
<div>
<son ref="son"></son>
</div>
<script>
component: { son},
mounted() {
const son = this.$refs.son;
// 不仅如此 还可以取到子组件son 中的data 和method
}
</script>
正是因为可以取到子组件件中的data,导致我犯了一个错误,而且是走进了死胡同,转牛角尖。
我的验证是一个下拉框验证,简单写 如下
<dropdown-select
ref="dropdownSelect"
:value="[rule.content.parser]" // 因为是循环出来的,value绑定的是for item的值,所以不好用变量来解决,最好的方式是用ref
@input="customParserInput(index, $event)"
/>
// 这个子组件的data中有一个 checkvalue 这样一个变量是显示值的,所以我是取值
const value = this.$refs.spanDropSelect.checkValue
我的问题就出现来,在页面初始渲染的时候,
console.log (this.$refs.spanDropSelect) // 有checkValue 也有值的是数组
console.log(this.$refs.spanDropSelect.checkValue) //拿不到值,显示为空数组
我想了很久才想明白,页面初始渲染,页面上有值,是因为上一次退出 我保存在了v-for 的数组里面,子组件里的checkValue 还是data里的 初始的状态,没有经过method方法进行赋值。
所以我对$ref 要判断的是 子组件的这一种情况 的处理办法是
<dropdown-select
ref="dropdownSelect"
:value="[rule.content.parser]" // 因为是循环出来的,value绑定的是for item的值,所以不好用变量来解决,最好的方式是用ref
@input="customParserInput(index, $event)"
/>
<span ref="spanDropSelect">{{rule.content.parser}}</span>
结合一开始说的, 给这个span的样式设为 透明,这样判断它的innerHTML即可。