更新列表数组中Javascript(Vue.js)对象中的单个项目

时间:2017-06-25 16:36:52

标签: javascript object vue.js

我有一个图库图片列表,我希望能够选择一个图像来制作它this默认情况下,总是必须有一个预览图像。 我想要的是

  1. 点击图片
  2. 删除所有图片上的预览
  3. 将点击的图片设为预览
  4. 更新API
  5. 这是我试图开始工作的代码:

    $con=mysqli_connect($host,$user,$password,$dbname);
    $sql="select num, ode_y from Topics order by num asc";
    
    $result = mysqli_query($con,$sql);
    
    $sql1="SELECT * from Topics ORDER BY num ASC";
    $result1=mysqli_query($con,$sql1);
    $rowno = mysqli_num_rows($result1);
    
    <span>Total $rowno registered 
    topics</span>
    
    while($row = mysqli_fetch_array($result))
    { 
        $odey1= ($row['ode_y']);
    
        $sql01="SELECT ode  
                from fltr2 AS s 
                    INNER JOIN Register AS r ON s.sender=r.sender 
                                and r.reg=0 
                                and s.ode='$odey1'";
    
        $result01 = mysqli_query($con,$sql01);
        $num01=mysqli_num_rows($result01);
    
     <div>Counts : ".$num01."</a>
     </div>
    }
    

    当我在方法中preview: true时,我确实会获得要更新的正确图像对象,但这不会更新export default { props: ['images'], methods: { makePreview (image, index) { // Loop through images and remove preview this.images.map((image, index) => { image.preview = false }) // Set clicked image to preview image.preview = true // Update API this.updateImages() } } } 道具。

    编辑:

    图像对象:

    console.log(image)

1 个答案:

答案 0 :(得分:1)

我不确定我们在你的问题中遗漏了什么,这段代码似乎有效。我看到的唯一主要区别是我注释了updateImages方法。

从技术上讲,这是一种你正在改变一个属性的情况,这通常是不受欢迎的。目的是传递属性,并将对这些属性的更改作为事件发送回父级。但是,对象和数组可以变异。

const images = [{
    alt: "New venue",
    id: 111,
    large: "https://radnomcdn.com/large.jpg",
    order: 2,
    preview: false,
    thumb: "https://radnomcdn.com/thumb.jpg"
  },
  {
    alt: "New venue",
    id: 222,
    large: "https://radnomcdn.com/large.jpg",
    order: 3,
    preview: false,
    thumb: "https://radnomcdn.com/thumb.jpg"
  },
  {
    alt: "New venue",
    id: 333,
    large: "https://radnomcdn.com/large.jpg",
    order: 4,
    preview: false,
    thumb: "https://radnomcdn.com/thumb.jpg"
  }

]

Vue.component("display-images", {
  template:`
    <div>
      <div v-for="image, index in images">
        {{image.preview}}
        <button @click="makePreview(image, index)">Preview</button>  
      </div>
    </div>
  `,
  props: ['images'],
  methods: {
    makePreview(image, index) {

      // Loop through images and remove preview
      this.images.map((image, index) => {
        image.preview = false
      })

      // Set clicked image to preview
      image.preview = true

      // Update API
      //this.updateImages()
    }
  },
  mounted(){
    this.makePreview(this.images[0])
  }
})

new Vue({
 el: "#app",
 data:{
   images
 }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
  <display-images :images="images"></display-images>
  <div style="margin-top:5em">{{images}}</div>
</div>