渲染vue.js组件并传入数据
问题描述:
我无法弄清楚如何呈现父组件,在页面的一部分上显示列表中的合同列表,以及当用户单击其中一个组件时,在页面的其他部分显示该特定合同的详细信息。渲染vue.js组件并传入数据
这里是我的苗条文件:
#contracts_area
.filter-section
ul
li.filter-item v-for="contract in contractsAry" :key="contract.id" @click="showContract(contract)"
| {{ contract.name }}
.display-section
component :is="currentView" transition="fade" transition-mode="out-in"
script type="text/x-template" id="manage-contracts-template"
div
h1 Blank when page is newly loaded for now
script type="text/x-template" id="view-contract-template"
div :apply_contract="showContract"
h1#display-item__name v-name="name"
的javascript:
Vue.component('manage-template', {
template: '#manage-contracts-template'
});
Vue.component('view-contract', {
template: '#view-contract-template',
props: ['show_contract'],
data: function() {
return {
name: ''
}
},
methods: {
showContract: function(contract) {
return this.name = contract.name
}
}
});
Vue.http.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content');
var contractsResource = Vue.resource('/all_contracts{/id}.json');
var contracts = new Vue({
el: '#contracts_area',
data: {
currentView: 'manage-template',
contractsAry: [],
errors: {}
},
mounted: function() {
var that = this;
contractsResource.get().then(
function(res) {
that.contractsAry = res.data;
}
)
},
methods: {
showContract: function(contract) {
this.currentView = 'view-contract'
}
}
});
基本上我想这样,当用户点击任何合同项目在.filter截面,它在.display部分显示该合同的数据。我怎样才能做到这一点?
答
总之,您可以将值绑定到prop。
.display-section
component :is="currentView" :contract="currentContract"
视图合同
props: ['contract']
合同面积
data: {
currentContract: null,
},
methods: {
showContract: function(contract) {
this.currentView = "view-contract";
this.currentContract = contract;
}
}
有多种方式在Vue的传递数据。
- 将值绑定到props。使用
ref
直接调用子组件的方法。 - Custom Events。请注意,要全局传递事件,您需要一个全局事件总线。
- 真理的单个中央源(即vuex)
我已经说明的方法1,2,3在Codepen
注意次和第三方法将后只工作你的组件已经被渲染。在你的情况下,由于你的currentView组件是动态的,当用户点击时,display-section组件还不存在;它将不会收到任何事件。所以他们的内容一开始就是空的。
要解决此问题,您可以直接从子组件中访问mounted()
中的$parent
,但是这会在它们之间创建耦合。另一种解决方案是创建组件,但它们是conditionally displaying。另一个解决方案将等待,直到子组件被安装,然后发射事件。
如果您的需求很简单,我建议绑定值到道具(),否则您可以考虑使用类似vuex的东西。
完美,非常感谢您的帮助!感谢您的深入解答,对我的巨大帮助,因为我刚刚开始使用Vue。 – asalgan