访问数据中的道具

时间:2018-03-21 10:18:02

标签: javascript vuejs2 vue-component

你能告诉我我做错了什么吗?我需要访问组件中数据对象中的props。

我已经定义了这样的组件:

  export default {
    components: {...},
    computed: {...},
    props: {
      userCode: {
        type: String,
        default: null
      }
    },
    data: () => ({
      options: {
        callback: function() {
          console.log(this.userCode) // prints undefined
          return ...;
        }
      }
    }),
    methods: {...},
    ...,
  }

我在路由器中定义的prop值如下:

{
  path: '/user/bbb',
  name: 'users',
  component: userView,
  meta: {
    requiresLoggedIn: true,
  },
  props: {userCode: 'XXX'}
}

当我尝试使用相同的组件在html中渲染此prop时,就像这个{{this.userCode}}一样,所以它可以工作并显示我传递的代码。如何访问选项数据对象中的prop?感谢。

1 个答案:

答案 0 :(得分:0)

Vue.js最佳实践除了this.userCode未定义的原因是因为在这种情况下回调函数定义了自己的this并且没有使用全局this。要使用全局,请使用

callback: () => {}

callback: function() {
    console.log(this.userCode) // prints undefined
    return ...;
}.bind(this)

您可以在此处详细了解箭头功能https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions