我已经定义了这样的组件:
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?感谢。
答案 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