pass some variable of a row in Vue.js as parameters to vue.js method and send out using axios

Viewed 171

I have a web app, used Django as backend, Vue.js for the frontend. In the cell, that's a button for every row, which is supposed to get the detail info of the row after click. So I want to pass some variable of a row in Vue.js as parameters to Vue.js method.

But I failed to do that, when I tried to click the button, it always submitted the form, but I have added type="button" already.

                <tbody>
            <tr v-for="(row, index) in filteredRows" :key="`isbn-${index}`">
                <td name="`title_${index}`" v-html="highlightMatches(row.title)">{{ row.title }}</td>
                <td v-html="highlightMatches(row.author)">{{ row.author }}</td>
              
               <td><button type="button" v-on:click="greet( $event, {{ row.title }})">Greet</button></td>
                <td name="`discipline_code_course_code_${index}`"  bgcolor= "white"><div contenteditable></div></td>
                          </tr>
            </tbody>

<script>
             const app = new Vue({
        el: '#app',
        data:() => ({
            filter: '',
            rows: book_rows
        }),

        methods: {
                      greet: function (event, title) {
                alert(title);   #undefined when debug
                this.$http.post(
    '/check_code/',
    { title: title }
  );

}

        },
</script>

How could I pass some variable of a row in Vue.js as parameters to Vue.js method and send out using axios?

1 Answers

You need to use the verbatim tag, to ensure django does not strip those attributes from the template before JS uses them: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#verbatim

Wrap you JS template (currently within your django served HTML file) with the verbatim tag to ensure the bracketed vars are not parsed by django:

{% verbatim %}
<div>{{ app.jsVars }}</div>
{% endverbatim %}

You can check this by inspecting the source code of the produced HTML page (right click view source) - and your JS template variables should be there.


Quick note:

The code v-on:click="greet( $event, {{ row.title }})" might need inspecting, as if that's your title - you're applying it slightly differently in the row above:

v-html="highlightMatches(row.title) 

If it is a backend var, it needs speech-marks:

v-on:click="greet( $event, '{{ row.title }}')"
Related