gpt4 book ai didi

javascript - 如何在Vue组件中保存对 "this"的引用?

转载 作者:行者123 更新时间:2023-11-30 20:39:40 24 4
gpt4 key购买 nike

我不确定我这样做是否正确。请看看这个简单的 Vue 组件 Test.vue :

<template>
<div>
Hi from {{name}}
</div>
</template>

<script>
let self;

export default {
created: function () {
self = this;
},
methods: {
load() {
ajax().then((obj) => self.name = obj.data);
}
},
data() {
return {
name: 'one',
}
}
}
</script>

如您所见,我将其引用保存到名为 self 的变量中因为 this值lambda 函数的变化,例如ajax().then((obj) => self.name = obj.data);

我的问题是当创建另一个组件实例时,它会覆盖 self 的值在之前的例子中。例如,如果我有两个 <test id="1"></test><test id="2"></test>然后后面的组件会覆盖 self第一个的变量(同样发生在 v-for 中)。

所以我的问题是如何创建 self保存到 this 值的变量对于每个实例并且不会被覆盖?

编辑: 是的,我知道我可以做到 self = this在每个函数中,但这只是一个只有 1 个方法的简单示例。在我的实际组件中,我有 20 多个我不想做的功能 self = this在每个功能中。这就是为什么我可以创建一个变量,我可以在 create 期间分配一次。在任何地方调用和使用它(就像我们以前使用 that 变量一样)。

最佳答案

您尝试做的事情大多是不必要的

的确,this 的值在 JavaScript 中有时会令人困惑。不过,这也是一个众所周知的问题,具有众所周知的解决方案。

这些解决方案,至少在与 Vue 实例相关的问题中,是:

但不要相信我,让我们来看一个例子。获取您的源代码:

    methods: {
load() {
ajax().then((obj) => self.name = obj.data);
}
},

作为 .then() 的参数,您必须传递一个函数。此类函数中 this 的值将取决于您如何传递它

在第一种情况下(上述两个解决方案中的第一个解决方案),应该使用箭头函数(您已经这样做了)。所以,在你的代码中,self 是不必要的,因为箭头函数中的 this 仍然会指向 Vue 实例。

    methods: {
load() {
console.log(this.name);
ajax().then((obj) => this.name = obj.data);
}
},

在上面的示例中,两个 this.name 都引用了 same 属性。请参阅下面的演示。

const ajax = () => {
return fetch('https://api.myjson.com/bins/18gqg9')
.then((response) => response.json())
};

new Vue({
el: '#app',
data: {
name: 'Alice'
},
methods: {
yoo() {
console.log('outside:', this.name);
ajax().then((obj) => { this.name = obj.name; console.log('inside arrow, after change:', this.name); });
}
}
})
<script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script>
<div id="app">
<p>
name: {{ name }}
</p>
<button @click="yoo">AJAX!</button>

<p>Click the button above and check the console. The printed name variable is the same.</p>
</div>

现在,在第二种解决方案中,您将使用常规(非箭头)函数。但是要确保保留 this,您可以使用 .bind(this),如下所示:

    methods: {
load() {
console.log(this.name);
ajax().then(function (obj) { this.name = obj.data }.bind(this));
}
},

与前面的情况类似,在这两个地方 this.name 指的是同一个属性。请参阅下面的演示。

const ajax = () => {
return fetch('https://api.myjson.com/bins/18gqg9')
.then((response) => response.json())
};

new Vue({
el: '#app',
data: {
name: 'Alice'
},
methods: {
yoo() {
console.log('outside:', this.name);
ajax().then(function(obj) { this.name = obj.name; console.log('inside arrow, after change:', this.name); }.bind(this));
}
}
})
<script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script>
<div id="app">
<p>
name: {{ name }}
</p>
<button @click="yoo">AJAX!</button>

<p>Click the button above and check the console. The printed name variable is the same.</p>
</div>

因此,如您所见,在 Vue 实例中,不需要声明这样的 self 变量。

关于javascript - 如何在Vue组件中保存对 "this"的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49417410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com