前言
以下是Vue.js类的完整代码:
new Vue({
el: '#page',
data() {
return {
apipath: "http://bzc.xyz/",
posts: null,
};
},
//页面加载完成后运行
mounted() {
axios
.get(this.apipath + 'getposts.php')
.then(response => (this.posts = response.data))
.catch(function(error) {
console.log(error);
});
},
//自定义函
methods: {
getposts() { //返回Vue.js类内posts值
return this.posts;
},
}
})
防踩坑
其中在mounted中的get请求
axios
.get(this.apipath + 'getposts.php')
.then(response => (this.posts = response.data))
.catch(function(error) {
console.log(error);
});
还有methods中的getposts()函数
getposts() { //查看分类是否有子分类,并生成下拉菜单
return this.posts;
}
他们在访问Vue.js类内部的变量时必须要用this 例如 this.posts 否则就会出现报错:
ReferenceError: categories is not defined
at _e.havechildren ((index):188)
at _e.n [as havechildren] (vue.min.js:6)
at eval (eval at ui (vue.min.js:6), <anonymous>:3:582)
at _e.ie [as _l] (vue.min.js:6)
at _e.eval (eval at ui (vue.min.js:6), <anonymous>:3:516)
at _e.t._render (vue.min.js:6)
at _e.r (vue.min.js:6)
at go.get (vue.min.js:6)
at go.run (vue.min.js:6)
at Ot (vue.min.js:6)
另外在html中使用变量例如{{posts}}时加与不加this都行,但如果是多个vue类需要指明是哪个类的例如 a.posts 和 b.posts 。