【问题标题】:Vuejs passing options into a componentVuejs 将选项传递给组件
【发布时间】:2017-08-13 03:54:13
【问题描述】:

我有一个 vue 组件,它是一个滑块。

<Slider
  images= ['img/da-slide1.png', 'img/da-slide1.png']
  bg = "#000000"
  speed = 1
>
</Slider>

我想传递各种选项。我已经尝试了上面的代码,但没有任何运气。

我也想 v-for 图片出来

<div v-for="item in images">
    {{ item }}
  </div>>

可以吗?

【问题讨论】:

  • 太好了,我明白了,只是语法,但我如何 v-for 出来呢?

标签: javascript components vue.js


【解决方案1】:

您需要将图像数组作为属性传递,注意冒号:images:

<Slider
  :images="['img/da-slide1.png', 'img/da-slide1.png']"
  bg="#000000"
  speed="1"
></Slider>

还要记得在 Slider 组件中声明 prop props: ['images']

【讨论】:

    【解决方案2】:

    Vue.component( 'slider', {
    	template: '<div class="slider" :style="cBackgroundColor">' +
      	'<span v-for="(image, index) in images" :key="\'image\' + index">' +
        	'<img :src="image.url" :alt="image.alt" :title="image.alt"/>' +
        '</span>' +
      '<div>',
    	props: {
      	images: { type: Array },
        backgroundColor: { type: String, default: "#000000" },
        speed: { type: Number },
      },
      computed: {
      	cBackgroundColor: function() {
        	return 'background-color: ' + this.backgroundColor;
        }
      }
    });
    
    new Vue({
    	el: "#app"
    });
    .slider {
      display: inline-block;
    }
    
    img {
      width: 100px;
      height: 100px;
    }
    <script src="https://vuejs.org/js/vue.min.js"></script>
    <div id="app">
        <slider
          :images="[{ url:'https://vuejs.org/images/logo.png', alt:'Vue.js' }, { url: 'https://www.codementor.io/assets/page_img/learn-javascript.png', alt:'Javascript' }]"
          background-color="#9b42f4"
          :speed="1">
        </slider>
    </div>

    当你将属性传递给组件时,你必须使用“v-bind”或快捷键“:”,以防属性不是字符串:

    my-prop="you pass string here" <== when no "v-bind:" or no ":" this is a string
    
    :my-prop="you write here like in javascript"
    :my-prop="myVariable" <== myVariable is a javascript variable
    :my-prop="2" <== its the number 2 and not the string "2" !
    
    :my-prop="'use single quote to use string' + maVariable"
    :my-prop="[ 'array1', 'array2' ]"
    :my-prop="{ 'prop1': 'value1', 'prop2': 'value2' }"
    

    对于“v-for”使用“:key”。见v2.2.0

    当对组件使用 v-for 时,现在需要一个键。升级时您可能会看到一堆“软警告”,但这不会影响您应用的当前行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 2019-09-15
      • 2020-05-22
      • 1970-01-01
      • 2023-01-25
      • 2018-09-12
      • 1970-01-01
      相关资源
      最近更新 更多