gpt4 book ai didi

javascript - Vue.js - 从组件内的根实例访问数据

转载 作者:可可西里 更新时间:2023-11-01 02:09:47 26 4
gpt4 key购买 nike

这似乎是一个相当基本的问题,但我似乎无法找到明确(甚至有效)的答案。

我有我的根实例:

var vm = new Vue({
el: '#app',

// Data
data: {
events: {}
},

// Methods
methods: {

fetchEvents: function(){
this.$http.get('/api/events').success(function(theseEvents) {
this.$set('events', theseEvents);

}).error(function(error) {

});

}
},

ready: function(){

this.fetchEvents();

}

});

我有一个单独的组件,我想在其中列出存储在根实例中的事件。目前它看起来像这样:

var EventsList = Vue.extend({

template: '<ul><li v-for="event in events"><h2>{{ event.title }}</h2><p>{{ event.body }}</p></li></ul>',

data: function(){
return {
events: {}
}
},

methods: {

syncEvents: function(){
this.$set('events', this.$parent.events);
}

},

// When ready...
ready: function(){
this.syncEvents();
}
}

这似乎行不通。我也尝试过 this.$root.events 无济于事。解决这个问题的正确方法是什么?请记住,我想从根目录引用数据,而不是创建具有自己范围的副本。

编辑:尝试使用 Prop ,这里是列表组件,它也不起作用:

var EventsList = Vue.extend({

template: '<ul><li v-for="event in events"><h2>{{ event.title }}</h2><p>{{ event.body }}</p></li></ul>',

props: ['events']

}

最佳答案

Using props ,您可以轻松地将相同的数据从 parent 传递给 child 。由于我不知道您是如何将根实例和 EventList 链接在一起的,因此我假设您将其注册为全局组件。

文档指出:

Note that if the prop being passed down is an Object or an Array, it is passed by reference. Mutating the Object or Array itself inside the child will affect parent state, regardless of the binding type you are using.

因此,当您将同一个对象作为 prop 传递时,您将在所有组件中使用同一个对象。

var vm = new Vue({
el: '#app',

// Data
data: {
events: {}
},

// Methods
methods: {

fetchEvents: function(){
this.$http.get('/api/events').success(function(theseEvents) {
this.$data.events = theseEvents; // You don't need to use $set here

}).error(function(error) {

});

}
},

ready: function(){

this.fetchEvents();

}

});

事件列表:

var EventsList = Vue.extend({

template: '<ul><li v-for="event in events"><h2>{{ event.title }}</h2><p>{{ event.body }}</p></li></ul>',

data: function(){
return {
}
},
props: {
events: Object, // assuming that your prop is an object
},
}

// Register the vue component globally, if you want to:
Vue.component('eventlist', EventsList);

在根 vue 实例模板中,您可以将根 vue 实例 events 作为子组件中名为 events 的属性传递:

<div class="app">
<!-- events is passed using the :events prop -->
<eventlist :events="events">
</eventlist>
</div>

关于javascript - Vue.js - 从组件内的根实例访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35723595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com