我有一个定义如下的 Vue.js 组件:
module.exports = Vue.component('folder-preview', {
props: ['name', 'path', 'children', 'open'],
template: `...
`,
methods: mapActions([
]),
computed: mapState([
]),
data: ()=> {
console.log(this);
return {
collapsed: (this.open !== 'true')
}
}
});
基本上,我试图将 collapsed
作为组件的本地数据,但将 prop 中传递的值作为初始值。但是,似乎 this.open
始终未定义。事实上,console.logging this
打印了一个空对象,我似乎不明白为什么。
我是不是搞错了什么?
最佳答案
您的代码中的问题很微妙:您已将数据声明为箭头函数。
如 this question 所述,箭头函数从定义的上下文中获取 this
,而常规函数从调用上下文中获取 this
。使 data
成为箭头函数意味着它无法正确接收组件作用域。
当声明为不在 this
范围内关闭的常规函数时,该组件工作正常。
Vue.component('sample', {
props: ['open'],
template: '<div>{{collapsed}}</div>',
data() {
return {
collapsed: this.open !== 'true'
}
}
})
new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<sample open="true"></sample>
</div>
关于javascript - Vue组件数据函数——the为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46230254/