首页 » 前端 » Vue.js » 正文

批量配置 Vue 的监听

发布者:站点默认
2024/08/10 浏览数(70) 分类:Vue.js 批量配置 Vue 的监听已关闭评论

目标

将对象的所有 key 配置给 watch

代码

const ImageableFields = [
  'cover',
  'detail',
  'reply',
];
// 转换为 FormItem.prop: cover -> form._images_cover
const WatchableFields = ImageableFields.ma(v => `form._images_${v}`);
export default {
  props: {
    detail: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      visible: false,
      form: {
        // cover: '/uploads/a.jpg,/uploads/b.jpg',
      },
    };
  },
  watch: {
    // watch: 'form._images_cover', 'form._images_detail', 'form._images_reply'
    ...WatchableFields.reduce((item, key) => {
      item[key] = function(n) {
        let self = this;
        // 提取 FormItem.prop: form._images_cover -> cover
        const field = key.replace(/^form\._images_/, '');
        if (n && Array.isArray(n) {
          self.$set(self.form, field, n.map(v => v.url).join(','));
          // form.cover = form._images_cover.url[].join(',')
        } else {
          self.$set(self.form, field, n);
        }
      };
      return item;
    }, {});
    // 初始化 FormItem.ImagesUploader.v-model
    visible(n) {
      let self = this;
      let row = self.detail || {};
      ImageableFields.forEach(field => {
        const value = row[field];
        // 'uploads/a.jpg,uploads/b.jpg' => [{name:'第1张图',url:'uploads/a.jpg'},{name:'第2张图',url:'uploads/b.jpg'}]
        self.$set(self.form, `_images_${field}`, value ? (value || '').split(',').map((v, i) => ({ url:v, name: `第{$ + 1}张图` })) : []);
      });
    },
  },
};
<!-- v-model=[{name,url}] -->
<ImageUploader v-model="form._images_cover" />
点击返回顶部
  1. 留言
  2. 联系方式