背景

在使用Vue开发时,遇到了这样一个问题。如下所示:

 [Vue warn]: The computed property "fields" is already defined in data.

image.png

问题分析

  1. 锁定问题
    很明显问题是fields属性被重复声明了多次。
  2. 查询位置
    于是开始在整个项目中搜索fields字段。由于笔者使用PHPStorm,很简单就可以实现find in path,但竟然没搜到。
  3. 分析问题
    因为笔者在开发时,默认忽略了node_modules文件,所以问题一定出现在我引用的哪个包,与现有包产生了冲突。
  4. 继续探索
    由于项目初始,笔者仅引用了两个包,其一为ElementUI,其二为vee-validate
  5. 精确锁定问题
    于是,查阅了一下文档,发现了vee-validate作者很有先见预料了这个问题,在他的文档里的配置项Configuration里面是这样写的。
import Vue from 'vue';
import VeeValidate from 'vee-validate';

const config = {
  errorBagName: 'errors', // change if property conflicts.
  fieldsBagName: 'fields', 
  delay: 0, 
  locale: 'en', 
  dictionary: null, 
  strict: true, 
  enableAutoClasses: false, 
  classNames: {
    touched: 'touched', // the control has been blurred
    untouched: 'untouched', // the control hasn't been blurred
    valid: 'valid', // model is valid
    invalid: 'invalid', // model is invalid
    pristine: 'pristine', // control has not been interacted with
    dirty: 'dirty' // control has been interacted with
  },
  events: 'input|blur',
  inject: true
};

Vue.use(VeeValidate, config);

在config对象中,可以清楚的看到fieldsBagName:fields配置项,在errorBagName注释中可以看到,change if property conflicts,意思就是在发生属性冲突的情况下,去更改它。

解决问题

最终的解决方法就是:

// 使用vee-validate(会报冲突, 因为elmentui中fields属性已使用)
import VeeValidate from 'vee-validate';
const config = {
    errorBagName: 'errorBags', // change if property conflicts.
    fieldsBagName: 'fieldBags',
};
Vue.use(VeeValidate, config);

然后,效果是这样的(嘿嘿嘿):

 

Logo

前往低代码交流专区

更多推荐