Search code examples
htmlvue.jsvuejs2scopingelement-ui

Scoping Issue in Table when trying to access a specific row in a dilaog box (Vue.js, Element-ui)


I have created a table using el-table (Element-ui) in Vue.js. I want to access a specific row in the table when clicked on a button in that row, but the catch here is that after clicking on the button, a dialog box should open up and then access that specific row. When I try to access the row outside of the dialog box using scope.row, it works perfectly fine but it does not work properly when accessed inside teh dialog box, instead it runs in a loop till the end of the table.

Please find the code below:

        <el-table-column prop="count"
                   label="Total">

                   <template slot-scope="scope">
                      <!-- {{fetchData(scope.row)}} When scope.row is accessed here, it works perfectly--> 

                      <el-button type="text" @click="dialogVisible = true">{{scope.row.count}}</el-button>
                      <el-dialog
                        :visible.sync="dialogVisible"
                        :before-close="handleClose">

                   <!--I want to access the speicfic row clicked here, but it ends up looping through the table and doesnt send that specific row only. -->
                           {{fetchData(scope.row)}}
                           
                      </el-dialog>
                   </template>
                </el-table-column>

Can someone please suggest some solution to this issue in the above code? I am stuck on this for while. Would appreciate it.

Thank you.


Solution

  • This is a table... So fetchData will be called for each row as your code sits now.

    But if you attach fetchData on the button instead, it will work. But then you would have to add a variable to the mix, or use a computed property. Anyways, I don't like calling functions in template, handle that logic in script or using computed properties. So here's what I'd do:

    data() {
      return {
        chosenRow: null
      }
    },
    methods: {
      fetchData(row) {
        this.chosenRow = row;
      }
    }
    

    Template:

    <template slot-scope="scope">
      <el-button type="text" @click="fetchData(scope.row); dialogVisible = true">
        {{ scope.row.follower_count }}
      </el-button>
      <el-dialog :visible.sync="dialogVisible">
         {{ chosenRow }}      
      </el-dialog>
    </template>
    

    or just assign the row in template...

    @click="chosenRow = scope.row; dialogVisible = true"