目的:为vue 2.x项目的v-for全局注入data-index
代码:
// vueVForHook.js
export default {
install (app, options = {}) {
try {
const indexName = options.indexName || 'data-index'
const oldFun = app.prototype._l
const newFun = function () {
const arg = arguments
const oldParams = arg[1]
arg[1] = function () {
const result = oldParams(...arguments)
const attrs = result.data.attrs || {}
attrs[indexName] = arguments[1]
result.data.attrs = attrs
return result
}
return oldFun(...arg)
}
app.prototype._l = newFun
} catch (e) {
console.error('Hook Vue v-for Filed:', e)
}
}
}
使用:
// main.js
import Vue from 'vue'
import App from './App.vue'
import VueVForHook from './vueVForHook'
Vue.use(VueVForHook)
new Vue({
render: h => h(App),
}).$mount('#app')
效果:
<div data-index="0">0</div>
<div data-index="1">1</div>
<div data-index="2">2</div>
<div data-index="3">3</div>
<div data-index="4">4</div>
...
该方案已发布为npm包:vue-v-for-hook
使用方式
npm i vue-v-for-hook --save
// main.js
import VueVForHook from 'vue-v-for-hook'
Vue.use(VueVForHook, {
indexName: '自定义index名称,可选,默认为data-index'
})