Vue JS按唯一ID删除数组中的对象?

时间:2016-11-10 04:10:25

标签: javascript vue-component vue.js

我正在使用Vue.js删除对象数组中的对象,问题是我无法通过它的唯一ID找到删除对象的方法。我正在使用vue.js版本1.我还需要一种方法来更新同一个对象(它必须是被动的,所以我的视图会自动更新)。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue Js - components</title>
</head>
<body>


<!-- index.html -->
<div id="app">
  <div class="container-fluid">
    <ul class="list-group">
      <post v-for="posty in posts" :posty="posty" track-by="uuid"></post>
    </ul>
  </div>
</div>

<template id="my-component">
	<div v-if="posty.votes === '15'">
	  <button v-on:click="testFunc(posty.uuid)">{{posty.title}}</button>
	</div>
	<div v-else>
	  <button v-on:click="testFunc(posty.uuid)">No</button>
	</div>
</template>



<script src="vue-v1.js"></script>
<script>
Vue.component('post', {
  template: "#my-component",
  props: ['posty'],
  methods: {
  	testFunc: function(index){
  		 this.$parent.parentMethod(index);
  	}
  }
});

var vm = new Vue({
  el: "#app",
  data: {
    posts: [{	uuid: '88f86fe9d',
				title: "hello",
				votes: '15'
			},
			{	
				uuid: '88f8ff69d',
				title: "hello",
				votes: '15'
			},
			{	
				uuid: '88fwf869d',
				title: "hello",
				votes: '10'
			}]
  },

  methods: {
  	parentMethod: function(index){
  		Vue.delete(this.posts, index);
  	}
  }
});
</script>	
</body>
</html>

1 个答案:

答案 0 :(得分:1)

https://jsbin.com/fafohinaje/edit?html,js,console,output

我不知道你的Vue.delete方法应该代表什么,所以你可以选择数组拼接

methods: {
  parentMethod: function(index){
    this.posts.splice(index, 1)
  }
}