Vuejs - 将查询字符串值获取到组件中

Vuejs - getting a querystring value into a component

我有一个这样的查询字符串:

https://someurl.com?q=test

我有一个这样的组件:

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>
`
})

但是,这不起作用。我希望能够将查询字符串中 'q' 的值传递给这行代码:

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

我该怎么做?

您必须在组件上下文中定义 q 变量。您可以使用道具(在组件实例化时设置值)这样做,但在您的用例中,从通过 v-for 使用的 result 对象检索其值是有意义的。 检查以下代码段以获取 'query in props' 和 'query in result' 示例。 您必须 know/define 此查询值的来源。您的 results 项或父组件

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>