Vue.js更新组件中已创建函数的数据

问题描述 投票:0回答:3

我无法从created()函数更新数据属性。我也尝试使用'this',但我似乎超出了范围。有帮助吗?无论如何,兄弟组件在点击时发出信息,该组件应该接收并显示为数据,非常简单,但是当我尝试更新数据的主要属性时,它们总是保持不变。我是vue2的新手,所以任何帮助将不胜感激。

const singleAc = Vue.component('singleAc', {
template: `<div class="helper_text">
            <div>  Aircraft with ID : {{ $route.params.aircraftId }} </div>
            <div><img class="airline_logo" src="//logo.clearbit.com/Ryanair.com"></div>
            <div>  Model : {{modelName}} </div>
            <div v-if="fromAp">  From: {{fromAp}} </div>
            <div v-if="toAp">  To: {{toAp}} </div>
         </div>`,
data: function() {
    return {
        company: null,
        modelName: null,
        fromAp: null,
        toAp: null

    }
},
created() {
    bus.$on('op', function(op) {
        singleAc.company = op;
        console.log(op)
    })
    bus.$on('model', function(model) {
        singleAc.modelName = model;
        console.log(model)
    })
    bus.$on('from', function(from) {
        singleAc.fromAp = from;
        console.log(from)
    })
    bus.$on('to', function(to) {
        singleAc.toAp = to;
        console.log(to)
    })
}
});
javascript object vuejs2 this
3个回答
0
投票

暂时忘记全球事件,尝试使用props传递您的飞机数据,然后您的组件应通过添加以下内容来访问飞机数据:

props: ['aircraft']

不要忘记指向飞机数据模型。它应该看起来像这样:

`<div :aircraft="aircraft" class="helper_text">
        <div>  Aircraft with ID : {{ aircraft.id }} </div>
        <div><img class="airline_logo" src="//logo.clearbit.com/Ryanair.com"></div>
        <div>  Model : {{aircraft.modelName}} </div>
        <div v-if="fromAp">  From: {{fromAp}} </div>
        <div v-if="toAp">  To: {{toAp}} </div>
     </div>`

希望能帮助到你。


0
投票

singleAc是Vue组件,而不是Vue实例。这就是改变像singleAc.company这样的数据不起作用的原因

你仍然需要使用this

解决方案1:use arrow functions so that this can be used

const singleAc = Vue.component("singleAc", {
    created() {
        bus.$on("op", op => {
            this.company = op;
            console.log(op);
        });
    }
});

解决方案2:将this存储在变量中

const singleAc = Vue.component("singleAc", {
    created() {
        var _t = this;
        bus.$on("op", op => {
            _t.company = op;
            console.log(op);
        });
    }
});

希望这可以帮助。


0
投票

绑定这实际上解决了问题

 bus.$on('to', function(to) {
     this.toAp = to;
 }.bind(this))
© www.soinside.com 2019 - 2024. All rights reserved.