代码之家  ›  专栏  ›  技术社区  ›  Andrew Dunn

从观察程序回调调用Vue组件属性“undefined”

  •  1
  • Andrew Dunn  · 技术社区  · 6 年前

    我为一个电子学习网站的讲师API编写了一个Vue客户端,该网站为该讲师所教的每门课程获取相关的问答线索。

    客户首先填写课程列表。

    接下来,单击某个课程时,该课程的ID将作为一个名为 courseid ,这样子组件本身就可以使用该ID执行API查找以获取该课程的线程。

    子组件包含一个方法,该方法执行API请求以获取调用 getThreads ,使用道具 课程编号 作为该请求中的参数。

    最后,一个观察者看着道具 课程编号 和电话 获取线程 如果它改变了。至少应该这样。

    当我单击父组件的课程列表中的课程时,该课程的ID将作为属性成功传递给子组件 课程编号 (the 课程编号 在vue devtools面板中,prop以正确的值显示,但浏览器控制台显示以下内容:

    [Vue warn]: Error in callback for watcher "courseid": "ReferenceError: courseid is not defined"
    

    以下是 <script> 上述子元素的节:

    <script>
    import axios from 'axios';
    
    export default {
      name: 'qAndAThread',
      data() {
        return {
          axiosResult: [],
          isLoading: false,
        };
      },
      props: {
        courseid:{
          default: '',
          type: String
        },
      watch: { 
        courseid: function () {
          this.getThreads();
        },
      },
      methods: {
        getThreads: function makeRequest() {
          this.isLoading = true;
          const token = '*redacted*';
          const instance = axios.create({
            baseURL: '*redacted*',
            timeout: 100000,
            headers: {
              Accept: '*/*',
              'Content-Type': 'application/json;charset=utf-8',
              Authorization: `bearer ${token}`,
            },
          });
    
          instance
            .get(`/courses/${courseid}/questions/?page_size=200`)
            .then((response) => {
              this.axiosResult = response.data;
              this.isLoading = false;
              this.unread = this.axiosResult.count;
            })
            .catch((error) => {
              //console.log(error);
              this.axiosResult = error;
              this.isLoading = false;
            });
        },
      },
    };
    </script>
    

    如有任何帮助,我们将不胜感激!

    1 回复  |  直到 6 年前
        1
  •  1
  •   mwilson    6 年前
    .get(`/courses/${courseid}/questions/?page_size=200`)
    

    应该是

    .get(`/courses/${this.courseid}/questions/?page_size=200`)
    

    courseid 在你的目标上所以离开 this 将使它 undefined . 如果你这样做了 this.courseid 它应该起作用。

    我不知道如何 vue 保持范围,但您可能还需要这样做:

    watch: { 
        courseid: function () {
          this.getThreads();
        },
      },
    

    可能需要

    watch: { 
        courseid: function () {
          this.getThreads.bind(this);
        },
      },