鍍金池/ 問(wèn)答/HTML/ Vue - 在v-for中異步操作修改樣式問(wèn)題

Vue - 在v-for中異步操作修改樣式問(wèn)題

遇到的問(wèn)題,抽象之后,大致是這樣,麻煩各位看看如何解決?

  • 頁(yè)面的數(shù)據(jù)通過(guò)v-for渲染,id屬性為index
  • 點(diǎn)擊按鈕,服務(wù)器返回樣式,大致是這樣:{1:{height:'200px'}}
  • 根據(jù)返回樣式,修改對(duì)應(yīng)的元素樣式(注:不能使用DOM操作)
  • HTML代碼如下:
<ul>
    <li v-for="(item, index) in items" :id="index">{{item}}</li>
    </ul>
    <button @click="change">設(shè)置高度</button>
</ul>
  • js代碼如下:
data: {
    items: [1, 2, 3]
},
methods: {
    change() {
        // 模擬異步請(qǐng)求數(shù)據(jù)
        setTimeout(() => {
            // key中1/2/3代表每個(gè)li的id
            let list = {
                1: { height: '100px' },
                2: { height: '200px' },
                3: { height: '300px' }
            }
        }, 1000)
    }
}

在線(xiàn)編輯點(diǎn)這里

回答
編輯回答
凹凸曼

html:
:style="list[item]"
js:
datalist然后賦值改this.list={...}

2017年12月14日 20:55
編輯回答
風(fēng)畔
<div id="app">
    <ul>
        <li v-for="(item, index) in items" :id="index" :style="getStyle(item)">{{item}}</li>
    </ul>
    <button @click="change">設(shè)置高度</button>
</div>
new Vue({
    el: '#app',
    data: {
        items: [1, 2, 3],
        list: null,
    },
    methods: {
        change() {
            var vm = this;
            // 模擬異步請(qǐng)求數(shù)據(jù)
            setTimeout(() => {
                // key中1/2/3代表每個(gè)li的id
                vm.list = {
                    1: { height: '100px' },
                    2: { height: '200px' },
                    3: { height: '300px' }
                }
            }, 1000)
        },
        getStyle(item) {
            return (this.list || {})[item];
        }
    }
})

https://codepen.io/anon/pen/O...

2017年9月14日 16:37