vue中mounted方法访问数据接口获取数据,{{ 数据 }}访问却没有

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
    <div id="data">{{datas}}</div>
    <script type="text/javascript">
            new Vue({
                el:'#data',
                data:{
                    datas:null    
                },
                mounted:function(){
                        const params = new URLSearchParams();
                        params.append('type', 'queryHeadCarousel');
                        axios
                        .post('https://xxxx/php.php',params)
                        .then(function(response){
                            
                            this.datas = response;
                            console.log(this.datas);

                        })
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        })
                  }
                
            })
        
            
    </script>
</body>
</html>

我在mounted周期中访问数据接口并取得数据对象,并赋给datas,此时控制台打印datas含有数据,但是在dom中访问{{datas}}却为空?
初学vue,各位能不能帮忙解解惑?

//////////////////////////////

找到原因了,下面第一种写法就行,第二种就不行。
弱弱问一句有啥区别吗?0.0

第一种:
.then(response => (this.datas= response.data))

第二种:
.then(function(response){
this.datas = response.data;
})

阅读 6.9k
2 个回答
  1. axios 返回的 response 本身是对象,你要的如果是 http 返回的文本内容,应该访问 response.data
  2. 对于 vue 实例上的数据,赋予如字符串或数字的值是没问题的。
    但如果要赋予对象值,你需要使用 Vue.set:

    this.$set(this, 'datas', response);
  3. 在 Template 中使用 {{ var }} 这样的格式只能打印 字符串 (或数字),请确保你的 datas 是字符串才能正确输出。
  4. function 的 scope 不正确,如果你使用「function () {}」 这样来定义闭包的话,在闭包内的 this 会是闭包本身。如果你想要使用与闭包当前上下文相同的 this 的话,需要使用 arrow function (箭头函数),或是指定这个 this 给其他变量:
    使用 function

    mounted() {
      this; // 这里的 this 是 Vue 实例
      axios.get('url')
        .then(function (response) {
          this.datas; // 这里的 this 变成了闭包
        })
    },

    使用 Arrow function

    mounted() {
      this; // 这里的 this 是 Vue 实例
      axios.get('url')
        .then((response) => {
          this.datas; // 这里的 this 与上下文相同
        })
    },

    定义一个 that

    mounted() {
      const that = this; // 这里的 this 是 Vue 实例,that 是 this 的 reference
      axios.get('url')
        .then(function (response) {
          that.datas;
        })
    },
新手上路,请多包涵

this 指向的问题吧,箭头函数this可以拿到this.datas

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题