定义指令 // common.js export const join = { bind (el, binding, vnode) { let value = binding.value if (Object.prototype.toString.call([]) !== Object.prototype.toString.call(value)) { throw new Error('请传入数组类型绑定值') } value.forEach((item, index) => { // 最后一个特殊处理-符 if (index + 1 === value.length) { el.innerHTML += `<a href="${item.url || 'javascript:void(0)'}">${item.name}</a>` } else { el.innerHTML += `<a href="${item.url || 'javascript:void(0)'}">${item.name} - </a>` } }) } } 引入使用 // xxx.vue <template> <div v-join="joinData"></div> </template> <script> import { join } from "@/directives/common"; export default { name: "app", directives: { join }, data(){ return{ // 数据格式 joinData: [ { name: "a", url: "http://www.baidu.com" }, { name: "b", url: "http://www.jd.com" }, { name: "c", url: "" } // 不需要链接的传空 ] } } } </script> 这种方式感觉复用性比较好,不知道你是否可以使用这种数据格式。
定义指令
引入使用
这种方式感觉复用性比较好,不知道你是否可以使用这种数据格式。