您的位置:首页 > Web前端 > Vue.js

vue created mounted this.$nextTick的使用场景

2020-07-21 04:09 1551 查看
  1. created
//组件创建之后
created() {
// 可以操作数据,发送ajax请求,并且可以实现
// vue对页面的影响 应用:发送ajax请求
console.log('组件创建后:'+this.msg);   //哈哈哈
}
  1. mounted
//装载数据到DOM之后
mounted() {
// 可以操作DOM
console.log('DOM装载后:'+document.getElementById('app'));  //<div id="app"><div id="test"></div></div>
}
mounted() {
// 可以通过ref属性获取按钮的DOM对象
console.log(this.$refs.btn);   //<button>按钮</button>
console.log(this.$refs.test);  //给组件绑定ref属性,得到组件的Vue对象 	VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
}
  1. this.$nextTick

如果要获取数据更新导致的DOM更新后的新DOM对象需要使用$nextTick回调
假如项目里有一个模态框是用v-i或v-showf控制显示隐藏的,当模态框出现后需要聚焦到input框

mounted() {
this.isShow = true;
// this.$refs.fos.focus();  //先更新DOM,然后直接这样写获取不了焦点。
// 因为实现相应式并不是数据发生变化后DOM立刻发生变化,
// 而是在$nextTick下次DOM更新结束之后的延迟回调,在回调函数中获取数据更新之后的DOM
this.$nextTick(function () {
this.$refs.fos.focus();
})
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: