首页 > 解决方案 > 在挂载函数中使用 vue.js 道具值

问题描述

我正在使用道具将值从一个 vue.js 组件传递到另一个。我在我的“mounted()”函数中使用了这个 props 值。我在下面设置的警报正确显示了从道具接收到的“this.Id”变量的填充值。但是,之后在 axios 帖子中使用相同的变量时未定义。这怎么可能?

 mounted () {
 this.$nextTick(function () {
   alert(this.Id)
   axios.post('/api/title', this.Id)
     .then((response) => {
     ...
     })
  })
 }

谢谢你。Ĵ

标签: javascriptnode.jsvue.js

解决方案


可能是因为上下文。试试这个,看看它是否有效:

mounted () {
  // arrow function
  this.$nextTick(() => {
    alert(this.Id)
    axios.post('/api/title', this.Id)
     .then((response) => {
       ...
     })
  })

  // or use bind, but I recommend the one above.
  // as it's much cleaner.
  this.$nextTick((function() {
    alert(this.Id)
    axios.post('/api/title', this.Id)
     .then((response) => {
       ...
     })
  }).bind(this))
}

推荐阅读