【问题标题】:split data into separate values and assign them in span tags in Vuejs将数据拆分为单独的值并在 Vuejs 中的 span 标签中分配它们
【发布时间】:2021-02-08 00:33:27
【问题描述】:

我想分隔一个由逗号连接的字符串并将其单独存储跨标签,以便我可以获得单个值。 我正在使用 Php 在 Vuejs 中工作,并使用 Axios 从数据库中获取数据。我在数据库中有一个product_color 值,通过逗号连接,就像这样Red,Black, White 并想像PHP explode() 函数一样将它分开。 下面的代码 感谢并为糟糕的英语感到抱歉。

<div class="card p-5" v-for="(single, index) in singleProduct" :key="single.id">
     <h5 class="colors">colors:
      {{ single.product_color }}
      //getting value like this Red,Black,White
      <span class="color orange not-available" data-toggle="tooltip" title="Not In store"></span>
      <span class="color green"></span>
      <span class="color blue"></span>
      </h5>
</div>


import axios from "axios";
export default {
  name: 'product-detail',
  data (){
    return {
       //data from api
       singleProduct: [],
       product_id: this.$route.params.product_id
    }
  },
  created(){
    this.fetchItem();
  },
  methods: {
    /* eslint-disable no-unused-vars */
        fetchItem(product_id) {
            axios
                .get(`http://localhost/vue/src/Api/api?action=fetchItem&product_id=${this.product_id}`)
                .then((res) => {
                    console.log(res);
          this.singleProduct = res.data.product_data;
                })
                .catch((err) => {
                    console.log(err);
                });
        },
  }
}

【问题讨论】:

标签: javascript php jquery vue.js vuejs2


【解决方案1】:

你可以在你的字符串上使用 js split() 方法来创建一个类似于 php 的 explode() 的数组。将其放入计算方法以创建数组,然后添加 v-for 循环以输出您的跨度:

data() {
    //your data attrs
},
computed: {
    productColors() {
        return this.singleProduct.product_color.split(',');
    }
},

然后在您的模板中:

<span v-for="productColors as color" :class="'color '.color">{{color}}</span> 

【讨论】:

  • 我应该把这一行放在哪里 this.colorsArray = colorsString.split(',');对不起,我是新手
  • @KashmiriAmmar 抱歉,这是一个旧的(而且很糟糕)的例子。重新加载页面,您应该会看到一些更好的代码。
  • TypeError: 无法读取未定义的属性“product_color”
  • @KashmiriAmmar 两件事,我弄乱了变量名 - 应该是 return this.singleProduct.product_color.... (single to singleProduct,我更新了上面的例子)你应该等着展示你的产品直到它被加载。添加检查
猜你喜欢
  • 2020-12-16
  • 2012-05-23
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
相关资源
最近更新 更多