vue2(2.16.14) 中 data 数据定义为 data("this.xxx")的数据时, 方法里会取不到data? «这是一个有趣的问题,我暂时还没有去探究原因,不过可以给大家避坑。» 我有个 "test.vue" 组件 export default { name: 'test', data () { return { tabList: [{ label: '哈哈哈', value: 'hahaha' }, { label: '嘿嘿嘿', value: 'heiheihei' }], tab: this.tabList[0].value, } }, created() { console.log(this.tabList); this.show("created"); }, methods: { show(form) { console.log(`来自 ${ form }-- show被调用: `, this, 'tabList: ', this.tabList, 'tab: ',this.tab, 'method: ', this.test); }, test() { console.log(1111); } } } 我在其父组件中通过 "this.$refs.test.show('父组件')" 调用该方法时发现 this.data 为undefined,后面发现组件自身调用也存在这个问题。 "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241004/8d99370ec415c79c3b7105106e2fa31b.png) "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241004/37a6197bed9364023e54b3915bd827b3.png) 然而方法却能取到,暂时做个记录(如有大佬帮忙解开迷雾,十分感谢。
问题来自于"codewars The builder of things" (https://link.segmentfault.com/?enc=nc5rvEW%2FVPC95ltC06Zu6A%3D%3D.ET9zgztamRR4vYb51nQUTNP%2BfdbaJenm9axMcllAFB%2FlVWBApAPA6Qay%2B7S7R4tZUGv%2B8ren%2FKrCKOtguYWl985NIo%2BpZMkiXeErO5Pav7U%3D) 要求我们实现一个Thing类,其中一点要求如下所示: describe('#can', function(){ describe('jane.can.speak(phrase => `${name} says: ${phrase}!`)', function(){ it('should create a speak method on jane', function(){ const jane = new Thing('Jane'); jane.can.speak(phrase => `${name} says: ${phrase}!`); expect(jane.speak('hello')).to.equal('Jane says: hello!'); }); }); 难点是这里的"name"的值从哪里找啊? 我想到的一个方案是使用"with",但是codewars上使用的是严格模式,不能使用"with"。 class Thing { // TODO: Make the magic happen /* const jane = new Thing('jane'); console.log(jane.name) => 'jane' */ constructor(name) { this.name = name; /* can jane.can.speak(phrase => `${name} says: ${phrase}!`) jane.speak('Hello') => 'jane says: Hello!' where to find name ? => this */ this.can = { speak: (callback) => { this.speak = (...args) => { let res; with(this) { res = callback(...args); }; return res; } } } }