Small application project before did not use any framework, originally developed time too early, when small application ecology is not very mature, the recent project, want to put the previous code refactoring, choose wepy framework, chose wepy, because it is the most important reason is tencent open source framework, also met some problems in use, Keep a record of problems you encounter;
(1) In the app.wpy file, I have customized some methods, including the request encapsulation, according to the official documentation, the page can use this.$parent, as follows
app.wpy
doPost() {
console.log('app.wyp')
}
...
index.wpy // page页面
...
onLoad() {
console.log(this.$parent.doPost())
"app.wpy"
}
Copy the code
If only the simple page page use, that is not what the problem; If in the Component page, look like this
Index. wpy // page import wepy from'wepy';
import tel from '.. /components/tel'// Component pageexportDefault class Index extends wepy.page {components = {tel}} tel.wpy // import wepy from'wepy';
export default class Conchat extends wepy.component {
onLoad() {
console.log(this.$parent) // will point to the parent component console.log(this.$parent.$parent// will point to app.wpy}}Copy the code
Wepy official document is written so: https://tencent.github.io/wepy/document.html#/api? id=wepycomponent-class
Now there is another situation that can cause some problems. As we all know, Wepy is completely a VUe-like development style, and it also has mixin mixing functionality, which makes our development experience very good. Then the above problem, if we define a common method in mixin, as follows:
mixin.js
import wepy from 'wepy';
export default class ScanRed extends wepy.mixin {
onLoad() {
console.log(this.$parent.doPost()) } } index.wpy; . mixins = [mixin]; The output is"app.wpy"; tel.wpy; . mixins = [mixin]; The code will report an error,doThe Post method is undefinedCopy the code
This is because in tel.wpy, this.$parent points to index.wpy; This is where it gets a little awkward…
So in mixin-defined JS, we can use wepy.$instance
wepy.$instance === this.$parent //true
Copy the code
This is not mentioned in the official document, so it is probably not recommended for this method. In fact, when I encountered this problem, I also found that my previous writing method was a little wrong. The best way to deal with it is to create a separate JS file for custom methods and classes, so that there will be no such embarrassment.