在data()函数中使用Vue实例



首先,我知道它不是最佳实践,也根本不推荐使用,但在一些罕见的情况下,它可能会有用。举个例子,我使用一个外部js库来显示JSON内容,并且组件似乎接受了options属性。在这个属性中,我可以使用几个回调函数来验证JSON内容。

以下是实现:

<v-jsoneditor ref="editor"
v-bind:plus="true"
v-bind:options="options"
height="500px"
v-model="value"
v-on:error="onError">
</v-jsoneditor>

下面是数据函数。

data() {
return {
value: "",
options: {
mode: 'code',
onValidate(value) { //this is the function I am talking about
if (Vue.isRequired) {//need the Vue instance here because I can not say this.isRequered
console.log("required");
}
console.log(value);
return null;
}
}
}
}

我知道我可以有一个像下面这样的创建方法,并在vue实例上使用闭包:

async created() {
let vue = this;
this.options.onValidate = function (value) {
if (vue.isRequired) {
console.log("required");
}
console.log(value);
return null;
}
await this.loadRules();
}

但我希望有更好的方法,因为如果我不断添加越来越多像这样的回调函数,create方法看起来会非常复杂。

有没有更好的方法可以在data((函数中访问当前Vue实例?我正在使用的库就是这个。

似乎比我想象的要容易得多,完全忘记了更改data((以使用如下数组函数表示法:

data: (vue) => ({
value: "",
state: null,
errorMessage: "",
showRulesModal: false,
rules: [],
options: {
mode: 'code',
onValidate(json) {
let errors = [];
if (Object.keys(json).length === 0 && vue.isRequired) {
vue.$emit("on-value-validation-failed");
errors.push({
path: [''],
message: 'Value is required to continue'
})
return errors;
}
return null;
}
}
}),

感谢@Antoly为我指明了正确的方向:(

最新更新