vuex nextTick 使用
来源:8-4 vuex在项目中的应用(3)

Eden_frontend
2017-04-05
看视频中在mounted中使用dispatch调用actions里fetchOrderList
在computed调用store里的getters中getOrderList方法
那么我在created中使用
self.$nextTick(()=>{
_calculateHeight() {
let foodList=this.$els.foodsWrapper.getElementsByClassName("food-list-hook");
let height=0;
this.listHeight.push(height);
for(let i=0; i<foodList.length;i++){
let item=foodList[i];
height+=item.clientHeight;
this.listHeight.push(height);
}
}
});
请问在以上状态中怎么使用nextTick.老师能否写个例子给我。这问题困扰我好久了。谢 谢
7回答
-
你这么说我明白了,你可以通过action回调来计算dom高度
store里
const actions = { updateHeight({ commit, state }, cb) { Vue.http.post('/api/getOrderList', state.params) .then((res) => { state.orderList = res.data.list state.total = res.data.total cb && cb() }, (err) => { }) } }
组件:
mounted () { this.$store.dispatch('updateHeight', () => { // 这里的this.list已经更新,通过计算属性 this.$nextTick(()=>{ let foodList=this.$els.foodsWrapper.getElementsByClassName("food-list-hook"); let height=0; this.listHeight.push(height); for(let i=0; i<foodList.length;i++){ let item=foodList[i]; height+=item.clientHeight; this.listHeight.push(height); } }); }) }
action里也可以用promise,resolve 的时候就是 数据获取完毕,组件里通过then方法设置回调
const actions = { add ({ commit, state }) { // add 返回 promise对象 return new Promise((resolve, reject) => { setTimeout(() => { let newCount = state.count + 1 commit('updateNumber', newCount) commit('updateTimeStr', new Date().getTime()) resolve() }, 1000) }) } }
022017-04-06 -
fishenal
2017-04-05
我先说下我对你需求的理解,你是想页面dom更新以后,拿到元素的高度,加起来放到store里,对吗?
首先nextTick我没用过,我也不知道它的应用场景,如果你的目的仅仅是拿到$el里的元素对象,那么你完全可以在mounted阶段做。
其次,假如你的元素高度累价值是想存在store里,也没必要放到组件里,做法就是加好了,调用store的一个action
mounted () { //this.$nextTick(() => { let imgList=this.$el.getElementsByClassName("timg") let height = 0 let listHeight = [] for(let i=0; i<imgList.length;i++){ let item=imgList[i]; height += item.clientHeight; listHeight.push(height); } //更新完高度以后,更新store this.$store.dispatch('updateHeight', listHeight) // console.log(this.listHeight) // console.log(imgList[0].clientHeight) //}) }
00 -
Eden_frontend
提问者
2017-04-06
感谢老师的耐心回答
00 -
Eden_frontend
提问者
2017-04-05
我的获取dom的高 度真的无解了吗?
00 -
Eden_frontend
提问者
2017-04-05
谁能和我说一下怎么处理
00 -
Eden_frontend
提问者
2017-04-05
1 store里actions的ajax是异步的。
this.$store.dispatch('updateHeight', listHeight)
调用之前nextTick就已经执行了。无法获取高度。
2取数据是通过computed执行之后。nextTick无法获取到class="timg"
如果不使用vuex来管理数据的话我可以现在。但是使用之后就无效果
以下是我没使用vuex的方法
commonAjax.AJAX(APP.home,args,"POST",function (r) {
if(r.success){
self.$nextTick(()=>{//将nextTick放在ajax成功之后可以获取到动态的节点。如果放到actions不知道怎么写了
})
}
});
00 -
Eden_frontend
提问者
2017-04-05
现在是数据没拿到。无法计算高度。因为数据列表需要v-for出来之后才能拿到。
如果在mounted里计算高度是无效的。
let imgList=this.$el.getElementsByClassName("timg")
let height = 0
let listHeight = []
for(let i=0; i<imgList.length;i++){
let item=imgList[i];
height += item.clientHeight;
listHeight.push(height);
}
<li class="timg" v-for="item in itemList"></li>
022017-04-05
相似问题
回答 1
回答 1