如何将Vue组件导入Vue并替换值?

时间:2019-12-23 17:40:25

标签: vue.js import constants

我是VueJs的新手。 我需要在产品的每个页面中都加载模板,原则上并已加载该模板,并且将产品ID替换为模板

我正在其子Vue中导入template.vue

<template>
    <div id="app">
        <my-counter></my-counter>
    </div>
</template>

<script>
    import myCounter from './components/template.vue'

    export default {
        name: 'app',
        components: { myCounter }
    }

</script>

template.vue:

    <template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                     <div class="card-body">
                         <div v-for="product in products" class="row product-row">
<div v-if="product.id === count ">
                             <div class="col-md-4">
                                <img :src="product.picture" :alt="product.name">
                               </div>
                             <div class="col-md-8">
                                 <h2><b>{{ product.name }}</b></h2>
                                 <p>{{ product.price }}</p>
                               </div>
                            </div>
                         </div>
                     </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
 import axios from 'axios'
export default {
 name: 'somecomponent.vue', 
 props: { 
count: Number, 
// notice this is the same as the property passed in 
// value is the type to expect, Number, String, Object, etc
 },
        data() {
            return {
                products: [],

            }
        },

mounted() 
{ 
let vm = this
vm.getProducts(); 

},


methods: {
getProducts() {

                let vm = this
                axios.get('/api/products')
                    .then(function(response) {
                        vm.products = response.data.data  
                    })
           },
      },
}
</script>

如何在<div v-if="product.id === 'N' " >行替换常数?例如:5。

1 个答案:

答案 0 :(得分:0)

您可以通过几种不同的方式将数据传递给Vue组件。在您的情况下,添加property to the component可能是最容易的。

<template>
      <div id="app">
        <my-counter v-bind:count='myNum></my-counter>
      </div>
    </template>

    <script>
    import myCounter from './components/template.vue'

    export default {
      name: 'app',
      components: { myCounter },

      data: {
        myNum: 5
      }
    }

    </script>

在孩子中:

<template>
  <div v-if="product.id === count">
</template>

<script>

export default {
  name: 'myComponent',
  props: {
    count: Number,
    // notice this is the same as the property passed in
    // value is the type to expect, Number, String, Object, etc
  }
}

</script>