簡體   English   中英

動態添加按鈕並為其添加onclick功能

[英]Dynamically add buttons and add onclick function to it

我正在嘗試創建一個表並為每一行添加一個按鈕,然后該按鈕將調用一個自定義函數。 但是,無論我嘗試過什么都沒有用,我唯一能調用的函數是alert() 我在 Vuejs 中執行此操作並使用 java 腳本函數。 這是我的代碼:

<template>
    <div class="Main">
        <component :is="checkJWT()"/>
        <h3>{{organization_name}}</h3>

        <div> 
            <table id="workflowTable" style="width:100%"> <!-- the id can also be named organizationCaseTable -->
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                </tr>
            </table>
        </div>
    </div>
</template>

<script>
import jwt_decode from "jwt-decode";
    export default{
        data () {
            return {
                organization_name: ""
            }
        },

        methods: {
            checkJWT: function(){
                var access_token = document.cookie.split("=")[1];
                var decoded = jwt_decode(access_token)
                this.organization_name = decoded.azp

                this.getCaseInformation(this.organization_name)
            }, 

            getCaseInformation: async function(){
                fetch('http://localhost:3000/workflow-page/' + this.organization_name, {
                    method: "GET",
                    headers: {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
                        "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
                        "Content-Type": "text/plain",
                        "Authorization": "Bearer " + document.cookie["access_token"]
                    }
                })
                .then(response => response.json())
                .then(result => result.forEach(rec => {
                    var rowCol = "<tr><td style='border: 1px solid;text-align:center'>" + rec.id + 
                        "</td><td style='border: 1px solid;text-align:center'>" + rec.title + "</td>" + 
                        "<td><button id='viewWorkflow" + String(rec.id) + "' v-on:click='myFunction()'>View</button></td></tr>"
                    document.getElementById('workflowTable').innerHTML += rowCol
                }))
            }, 

            myFunction(){
                console.log("HERE")
            }
        }
    }
</script>

當我檢查按鈕元素時正在設置該屬性,但是當我單擊它時,沒有任何反應。 我還意識到.innerHTML將其添加為純文本,因此我嘗試了以下操作:

document.getElementById('workflowTable').innerHTML += rowCol行之后,我調用了一個名為this.makeClickable(rec.id)的函數,該函數如下所示:

 makeClickable(id){
                document.getElementById('viewWorkflow' + String(id)).setAttribute('onclick', 'myFunction');
            },

即使這樣,我也無法調用自定義函數,而且我不知道為什么或如何修復/繞過它。

避免直接改變 DOM。 這是很少見的事情,即使是一個好主意。 這適用於所有前端框架; 它們都基於 DOM 作為數據函數的相同原理工作。 我假設你正在尋找做這樣的事情......

<script>
export default{
  data () {
    return {
      organization_name: "",
      apiResponseData: null
    }
  },
  methods: {
    getCaseInformation(){
      fetch(myUrl)
        .then(d => d.json())
        .then(data => this.apiResponseData = data)
    },
    myFunction(record){
      console.log("selected", record)
    }
  }
}
</script>
<template>
  <div class="Main">
    <h3>{{organization_name}}</h3>

    <div>
      <span v-if="!apiResponseData">LOADING</span>
      <table v-if="apiResponseData" id="workflowTable" style="width: 100%">
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="rec in apiResponseData" :key="rec.id">
            <td style="border: 1px solid; text-align: center">{{rec.id}}</td>
            <td style="border: 1px solid; text-align: center">{{rec.title}}</td>
            <td>
              <button @click="myFunction(rec)">View</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

為了簡單起見,我在那里刪除了一堆東西,但這里有一些需要注意的地方。

  • 在數據加載之前, apiResponseData將為 null,因此您需要使用v-if="apiResponseData"僅在設置該值時呈現表或表行。 您也可以使用它來顯示加載指示器
  • v-for指令用於循環遍歷數據,它也應該使用一個鍵。 (不是強制性的,但在許多情況下很重要) 文檔
  • :key前面加了一個冒號定義,表示要解析的內容,否則視為字符串值
  • 您可以在按鈕myFunction(rec)中將記錄傳遞給您的函數。

此外,您不需要將函數定義為async ,因為您將其視為承諾(使用then

暫無
暫無

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

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