多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
在 Vue.js 组件上下文中,`this`指向了组件实例。因此当你切换到了不同的上下文时,要确保 `this` 指向一个可用的 `component` 变量。 换句话说,如果你正在使用 ES6 的话,就不要再编写 `var self = this;` 这样的代码了,您可以安全地使用 Vue 组件。 ### [](https://github.com/pablohpsilva/vuejs-component-style-guide/blob/master/README-CN.md#为什么-4)为什么? * 使用 ES6,就不再需要将 `this` 保存到一个变量中了。 * 一般来说,当你使用箭头函数时,会保留 `this` 的作用域。(译者注:箭头函数没有它自己的 this 值,箭头函数内的 this 值继承自外围作用域。) * 如果你没有使用 ES6,当然也就不会使用 `箭头函数` 啦,那你必须将 “this” 保存到到某个变量中。这是唯一的例外。 * 如果必须要使用的地方,定义为**var _this = this** ### [](https://github.com/pablohpsilva/vuejs-component-style-guide/blob/master/README-CN.md#怎么做-4)怎么做? ~~~ <script type="text/javascript"> export default { methods: { hello() { return 'hello'; }, printHello() { console.log(this.hello()); }, }, }; </script> <!-- 避免 --> <script type="text/javascript"> export default { methods: { hello() { return 'hello'; }, printHello() { const self = this; // 没有必要 console.log(self.hello()); }, }, }; </script> ~~~