簡體   English   中英

渲染 vue.js 組件並傳入數據

[英]rendering vue.js components and passing in data

我無法弄清楚如何呈現父組件,在頁面的一部分列表中顯示合同列表,當用戶單擊其中一個時,在另一部分顯示該特定合同的詳細信息這頁紙。

這是我的苗條文件:

#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-section 中的任何合同項時,它會在 .display-section 中顯示該合同的數據。 我怎樣才能做到這一點?

簡而言之,您可以將值綁定到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 中傳遞數據有多種方式。

  1. 將值綁定到props
  2. 使用ref直接從子組件調用方法。
  3. 自定義事件 請注意,要全局傳遞事件,您將需要一個全局事件總線。
  4. 單一的中心事實來源(即vuex

我在Codepen中說明了方法 1、2、3

請注意,第 2第 3方法僅在您的組件被渲染后才有效。 在您的情況下,由於您的 currentView 組件是動態的,並且當用戶單擊時,顯示部分組件尚不存在; 它還不會收到任何事件。 所以他們的內容一開始是空的。

要解決此問題,您可以從子組件直接訪問mounted()中的$parent ,但這會在它們之間產生耦合。 另一種解決方案是創建組件但有條件地顯示它們。 另一種解決方案是等到子組件已安裝,然后發出事件。

如果您的需求很簡單,我建議將值綁定到 props ( 1 ),否則您可以考慮使用 vuex 之類的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM