Vue.js访问类内变量时要用this

前言

以下是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 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值