Retrieving the content of a component tag in Vue

Recently, I've been experimenting with Vue and I'm interested in achieving the following:

<snippet name="Select From Table">
  SELECT *
  FROM database.table
</snippet>

I want to create a link that, when clicked, triggers a function allowing access to the SQL query.

I attempted using a component, but struggled to figure out how to retrieve the SQL within the click event. Although slots seem promising, it appears they only function within the tag itself and not as attributes.

Any suggestions or pointers would be greatly appreciated! Thanks!

Answer №1

If you're looking to extract the content of a slot, you can achieve this by iterating through this.$slots.slotName and accessing the innerText or innerHtml as needed.

Just a heads up: allowing client-side execution of SQL commands, as mentioned by @Terry, poses a significant security risk.

Check out the demo below:

Vue.component('v-test',{
    template:`
        <div>
          <a @click.stop="addText()">{{current}}</a>
        </div>
    `,
    data () {
      return {
        current: 'Bla'
      }
    },
    methods: {
      addText: function () {
        this.current += 'Bla'
      }
    }
})
Vue.component('snippet',{
    template:`
        <div style="border: 1px solid grey" @click="getHtml()">
            <slot></slot>
        </div>
    `,
    methods: {
      getHtml: function () {
        alert(this.$slots.default && Object.values(this.$slots.default).map((item, index) => {
          return item.elm && (item.elm.wholeText || item.elm.innerText)
        }).join('\r\n'))
      }
    }
})

new Vue ({
  el:'#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
    <div class="container">
        <snippet>Test SQL ...</snippet>
        <br>
        <snippet><strong>Te<i>s<span>.</span></i>t</strong> SQL ...</snippet>
        <br>
        <snippet><strong>Test<v-test></v-test></strong> SQL ...</snippet>
    </div>
</div>

Another approach is to utilize the ref property.

Vue.component('v-test',{
    template:`
        <div>
          <a @click.stop="addText()">{{current}}</a>
        </div>
    `,
    data () {
      return {
        current: 'Bla'
      }
    },
    methods: {
      addText: function () {
        this.current += 'Bla'
      }
    }
})
Vue.component('snippet',{
    template:`
        <div style="border: 1px solid grey" @click="getHtml()" ref="test">
            <slot></slot>
        </div>
    `,
    methods: {
      getHtml: function () {
        alert(this.$refs.test.innerText)
      }
    }
})

new Vue ({
  el:'#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
    <div class="container">
        <snippet>Test SQL ...</snippet>
        <br>
        <snippet><strong>Te<i>s<span>.</span></i>t</strong> SQL ...</snippet>
        <br>
        <snippet><strong>Test<v-test></v-test></strong> SQL ...</snippet>
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enforce file selection using AngularJS based on certain conditions

When data is received from the backend in JSON format, it looks like this: { "data":{ "xyz":[ { "number":"1", "short_text":"Sign Contract", "long_text":"Enter names after contract signing", "is_photo":false ...

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

Using Jquery to preserve the selected value in a radio button

Having two radio buttons, <div class="class1"> <span><input name="chk1" type="radio" checked="checked" id="check1"/>Option 1</span> <span><input name="chk2" type="radio" id="check2"/>Option 2</span> </div> ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...

``How does React facilitate the passing of properties from an API to a component?

I have two components - parentA and childB. I am trying to achieve a functionality where clicking a button in parentA triggers a function to fetch data from an API and then display it in the B component. On the surface, it seems like a simple task. Parent ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Performing an Axios post request with multiple parameters within a Vuex action

Utilizing axios to fetch API data within a vuex action: actions: { login ({commit}, payload) { axios.post(globalConfig.TOKEN_URL, { payload }) .then((resp) => { commit('auth_success', resp.data) }) .catch((err) => ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Ways to determine if a script is currently running within Node.js环境

In my Node.js script, I am importing a separate script that I want to be compatible with various JavaScript engines. Specifically, I only want the line exports.x = y; to run if the code is being executed in a Node.js environment. How can I determine this ...

Guide to authenticating users using Vue JS and Django

Currently, I am collaborating on a compact university venture utilizing Vue JS, Django2, and Django Rest Framework. The project involves two distinct user roles with varying actions within the application. The aspect that is leaving me puzzled is the logi ...

Fade-in with jQuery Javascript when clicked and fade-out once loading is complete

$('.showloader').click(function () { $('.loader').fadeIn(); }); I have a loading css called .loader It is default Display:none I want the .loader to be displayed when the .showloader is clicked. This will submit a registrati ...

Guide to attaching a click event in a subview of Backbone

I'm struggling with understanding event binding in a Backbone subview. Here's how my view is set up: TenantView = Backbone.View.extend({ events: { "click": "setActive" }, initialize: function() { this.parentEl = this.options.parent ...

Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug ...

Creating an associative array with this structure

var dictionary = { "cats": [1,2,3,4,5], "dogs": [6,7,8,9,10] }; What is the best way to create a similar array in JavaScript as shown above? I tried a method but it's not functioning correctly. var newArray = {}; newArray[keyName] = []; n ...

Top location for Cordova/Phonegap events in AngularJS

Currently, I am working on an AngularJS Cordova app and so far everything is progressing smoothly. My next objective is to integrate Cordova plugins into the application, specifically the Cordova Connect plugin, which will allow me to monitor network conne ...

Tips for manipulating specific URL redirection to an alternative URL within a NuxtJs application

Take this scenario, where the inputted URL is: http://localhost:3000/course-details The desired outcome should be a redirection to http://localhost:3000/courses I recall there being a method for achieving this, but it slips my mind at the moment. ...

Be patient for the complete loading of the image during an AJAX operation

My webpage includes an ajax action that loads a div containing an image on the left and text on the right. The issue I am facing is that the text loads first, aligned to the left, and then the image loads, causing the text to shift to the right, resulting ...

"Tempus Dominus now offering a seamless experience without the need for an

The example code provided seems to be malfunctioning: <button id="idbtn"> $('#idbtn').datetimepicker(); ...