Passing a querystring value to a Vue.js component

I am encountering an issue with passing a value from a querystring to my Vue component. The querystring looks like this:

https://someurl.com?q=test

My component is structured as follows:

Vue.component('externalrecipes', {
props: ['results'],
template: `
    <section>
        <div class="" v-for="result in results">
            <div class="card card-similar card-external text-center">
                <img :src="result.image_url" />
                <div id="meta" class="text-center">
                    <h5>{{ result.title }}</h5>
                    <a target="_blank" :href="'https://www.wine-searcher.com/find/' + q + '/1/uk'" role="button">Buy Wine</a>
                </div>
            </div>
        </div>
    </section>
`
})

Currently, I am struggling to pass the value of 'q' from the querystring to this specific line of code:

<a target="_blank" :href="'https://www.wine-searcher.com/find/' + q + '/1/uk'" role="button">Buy Wine</a>

Can anyone provide guidance on how to achieve this?

Answer №1

To successfully work with the q variable, it must be defined within the context of the component. One way to achieve this is by using props to set the value when the component is instantiated. In your scenario, it would be logical to extract the value from the result object accessed through the v-for loop. Refer to the snippet below for examples demonstrating 'query in props' and 'query in result'. It is important to understand/define where the query value originates from, whether it's from your results items or the parent component.

Vue.component('externalrecipes_props', {
props: ['results', 'query'],
template: `
    <section>
        <div v-for="result in results">
            <div class="card card-similar card-external text-center">
                <img :src="result.image_url" />
                <div id="meta" class="text-center">
                    <h5>{{ result.title }}</h5>
                    <a target="_blank" :href="'https://www.wine-searcher.com/find/' + query + '/1/uk'" role="button">Buy Wine</a>
                </div>
            </div>
        </div>
    </section>
`
});

Vue.component('externalrecipes_result', {
props: ['results'],
template: `
    <section>
        <div class="" v-for="result in results">
            <div class="card card-similar card-external text-center">
                <img :src="result.image_url" />
                <div id="meta" class="text-center">
                    <h5>{{ result.title }}</h5>
                    <a target="_blank" :href="'https://www.wine-searcher.com/find/' + result.query + '/1/uk'" role="button">Buy Wine</a>
                </div>
            </div>
        </div>
    </section>
`
});

new Vue({
  el: '#app',
});
.card {
  display: flex;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>
    <p>Include query in props</p>
    <externalrecipes_props :results="[
      {
        title: 'Some result',
        image_url: 'https://via.placeholder.com/100'
      }]" query="merlot" />
  </div>
  <div>
    <p>Include query in results items</p>
    <externalrecipes_result :results="[
      {
        title: 'Some result',
        image_url: 'https://via.placeholder.com/100',
        query: 'merlot'
      }]" />
  </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

Apply a red color or text-danger class to all text in a table row using Laravel and Vue.js

How can I make the entire text inside a row turn red if the fine is greater than 0 using v-if and v-else in Vue.js? I have working code below but it seems messy. Is there a better way to clean it up or optimize it?: <tr v-for="issue i ...

To achieve proper display of multiple boxes, it is essential for each box to be

My current approach involves adding boxes to the scene based on specific dimensions for height, width, and depth, and it works perfectly when the boxes are all square. https://i.sstatic.net/HdDSX.png However, the issue arises when I try to use a rectangu ...

Having trouble calling REST API in node.js, whereas it works perfectly fine when called from the browser?

My goal is to invoke the WebServer [mongoose embedded webserver] that is currently running on another machine. Here is the code snippet: var express = require('express'); var http = require('http'); var router = express.Router(); /* ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

AngularJS making a HttpPost request resulting in a 500-Internal Server Error

I'm currently working on an application where I need to include a user in the database which requires a POST operation. However, every time I try to run the application, I encounter a 500-Internal Server Error for the POST API call. Here is a snippe ...

What are the steps to refreshing a table using AJAX?

Struggling to update a table from my database, I have been following a PHP guide but can't get it to work. In a separate file, the data is retrieved and displayed in a table. I am attempting to use JavaScript to refresh this file. This code snippet ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Create a fresh array by extracting information from a different array column using the .map() function in Vue.js and Laravel

Here is the array I am working with: [ {product: "banana", quantity: "0", price: "32"} {product: "tomato", quantity: "1", price: "45"} {product: "mango", quantity: "2", price: "56"} ] My goal now is to create a new array containing only the product va ...

Striving to design an event planner with the datepicker feature in javascript

Currently, I am integrating a javascript datepicker into my project to facilitate displaying a calendar and selecting a date for adding/viewing/editing events on that specific date. On my view, the datepicker calender is displayed within a div element. & ...

Use Vue and axios to retrieve images from imgur

When attempting to retrieve all images from the Galleries template, I encounter the error/warning message saying: "Property "token" was accessed during render but is not defined on instance". Instead of displaying the images, I see: <img src="function ...

Struggling to make addClass and removeClass function correctly for the development of the unique "15 puzzle" game

I am currently in the process of creating a version of "the 15 game" using jQuery in HTML. You can find more information about the game on this page. The objective of the game is to rearrange a table of "boxes" in ascending order from 1 to 15. Below is th ...

Exploring (nested) data structures in JavaScript

I'm struggling to understand if my issue lies in how I am organizing my array or in how I am accessing it. The idea is simple: I want to have an array of car makes and models that I can access for display purposes. const carBrands = [ { Audi: { ...

saving a JSON element in a JavaScript array

Currently, I am utilizing AJAX to fetch data from a database using PHP and then converting it into JSON format. <?php echo json_encode($data); ?> This is the AJAX function being used: ajaxCall("getdata.php", container, function (data) { var co ...

Use the Nodejs HTTP.get() function to include a custom user agent

I am currently developing an API that involves making GET requests to the musicBrainz API using node.js and express. Unfortunately, my requests are being denied due to the absence of a User-Agent header, as stated in their guidelines: This is the code sn ...

I'm experiencing some strange symbols on my page that look like ''. It appears to be a problem occurring between the servlet and the Javascript. How can I resolve this issue?

After retrieving a CSV file from my servlet, I noticed that characters like 'é', 'á' or 'õ' are not displaying properly on my page. Strangely, when I access the servlet directly via browser, everything appears fine. I atte ...

Position an element in the middle of the range between the tallest and shortest characters

Is there a way to vertically center an element between the tallest and shortest characters of another element (preferably using just CSS, but JavaScript is also acceptable)? I want it to be aligned with the actual text content rather than the line height, ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

Using regular expressions, eliminate the element from a JSON object that contains a specified property

Imagine I have a string representing a JSON object. It could be invalid, with some params that will be replaced by another system (e.g. %param%). The task at hand is to remove all objects with a known propertyName equal to "true" using regex. { "someT ...