vue中的this.$refs,this.$emit,this.$store,this.$nextTick的使用方式
作者:raoxiaoya
this.$refs,this.$emit,this.$store,this.$nextTick的使用
this.$store
是vue用到了状态管理工具 vuex,就是一个保存全局数据的库。
this.$nextTick()
官方解释:
在下次 DOM 更新循环结束之后执行延迟回调。
有些操作(比如 this.$refs)需要在确保DOM被渲染完成后才能调用成功,这样就需要写在 this.$nextTick() 里面了。
this.$refs
我们在标签或者组件上定义 ref属性,比如在el-form上定义 ref="form1",这样我们就可以使用this.$refs.form1.validate(...)来访问这个组件中定义的属性和方法,因为 Element-ui 为 el-form 定义了 validate 方法。
1、如果ref名称是动态的呢,即 this.$refs.refName ,而 refName 是个变量(比如函数的参数),此时需要使用中括号,即 this.$refs.[refName].xxx
2、如果使用的:ref="xxx"来定义的,则应该是 this.$refs.[refName][0].xxx
3、ref 是在渲染完成之后才会有的,因此在调用 this.$refs.refName.xxx 的时候要确保 refName 这个DOM已经被渲染出来了,最典型的就是 ueditor,我们需要在它被渲染出来之后才能去调用组件的 set 方法去填充编辑器的内容,但是你并不知道它什么时候能渲染成功,只能使用延迟的方式,比如 this.$nextTick(() => {}),或者 window.setTimeout(() => {}, 500)
4、同样的,由于 this.$refs 不是响应式的,如果通过它来访问标签或组件的属性,需要在 this.$nextTick(() => {}) 之内。
this.$emit
this.$emit()主要用于子组件像父组件传递事件与参数。
上面说到,父组件可以使用 this.$refs 访问子组件;这里的 this.$emit 就是子组件用来触发父组件的事件。
<body>
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</body>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1;
this.$emit('increment', "参数"); // increment 是自定义的事件
}
}
});
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function (e) {
this.total += 1;
console.log(e);
}
}
})
</script>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
