英文:
I can't call a mixin function inside a javascript function
问题
我正在使用 Nuxt.js 进行一个小项目,目前我已经创建了一个使用 mixin 的插件,如你所见,但我不知道为什么函数 b 在渲染函数内部不起作用:
import Vue from 'vue'
Vue.mixin({
methods: {
a () {
const render = function () {
this.b()
}
render()
},
b () {
alert('testme')
}
}
})
英文:
i'm working on a small project using nuxt.js and right now i have created a plugin using mixin as you can see, but i don't know why function b doesn't work inside render function :
import Vue from 'vue'
Vue.mixin({
methods: {
a () {
const render = function () {
this.b()
}
render()
},
b () {
alert('testme')
}
}
})
答案1
得分: 3
自从您使用function关键字来定义render时,其中的this引用的是调用上下文(a),而该上下文没有b属性。
解决方案是使用箭头函数:const render = () => this.b();。
const methods = {
a() {
const render = () => {
this.b()
}
render()
},
b() {
alert('testme')
}
}
methods.a()
英文:
Since you used the function keyword to define render the this therein refers to the calling context (a) which has no property b.
The solution is to use an arrow function: const render = () => this.b();.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const methods = {
a() {
const render = () => {
this.b()
}
render()
},
b() {
alert('testme')
}
}
methods.a()
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论