在 vueJs 的方法内部使用计算属性

kvi*_*bar 7 vue.js computed-properties

我正在尝试在 vue.js 中创建一个随机播放函数。因此,为此我创建了一个计算属性,然后调用一个方法。但它不起作用。我创建了另外两个函数“添加”和“删除”,除了“随机播放”之外,这两个函数工作正常。

抛出错误:Uncaught TypeError: this.moveIndex is not a function

var app = new Vue({
  el: '#root',
  data: {
    tasks: [1,8,9],
    nextNum: 10
  },
  computed: {
    moveIndex: function(array){
      var currentIndex = array.length, randomIndex, tempVal;
      for(var i = currentIndex - 1; i > 0; i--){
        randomIndex = Math.floor(Math.random() * currentIndex);
        tempVal = array[i];
        array[i] = array[randomIndex];
        array[randomIndex] = tempVal;
      }
      return array;
    }
  },
  methods: {
    randIndex: function(){
      return Math.floor(Math.random() * this.tasks.length);
    },
    add: function(){
      this.tasks.splice(this.randIndex(),0,this.nextNum++)
    },
    remove: function(){
      this.tasks.splice(this.randIndex(),1)
    },
    shuffle: function(){
      var arr = this.tasks;
      arr = this.moveIndex(arr)
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
.bar-enter-active, .bar-leave-active{
  transition: all 1s;
}
.bar-enter, .bar-leave-to{
  opacity: 0;
  transform: translateY(30px)
}
.bar-move{
  transition: transform 1s 
}
.numbers{
  margin-right: 10px;
  display: inline-block
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

	<div id="root">
		<button @click="add">Add</button>
		<button @click="remove">Remove</button>
		<button @click="shuffle">Shuffle</button>
		<transition-group name="bar" tag="div">
			<span v-for="task in tasks" :key="task" class="numbers">{{task}}</span>
		</transition-group>
	</div>
Run Code Online (Sandbox Code Playgroud)

Vam*_*hna 6

计算属性只是返回值的 getter 函数,并且依赖于其他反应属性。

1.您的计算属性moveIndex只是修改数组数据属性,即this.tasks。所以就用一个方法来代替吧。

2.您尝试this.tasks使用索引直接修改数组的一项。Vue 无法检测到此类数组修改

所以用this.$set()orArray.prototype.splice()代替。

以下是变化:

var app = new Vue({
  el: "#root",
  data: {
    tasks: [1, 8, 9],
    nextNum: 10
  },
  methods: {
    randIndex: function() {
      return Math.floor(Math.random() * this.tasks.length);
    },
    add: function() {
      this.tasks.splice(this.randIndex(), 0, this.nextNum++);
    },
    remove: function() {
      this.tasks.splice(this.randIndex(), 1);
    },
    shuffle: function() {
      var array = this.tasks;
      var currentIndex = this.tasks.length;
      var randomIndex;
      var tempVal;

      for (var i = currentIndex - 1; i > 0; i--) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        tempVal = array[i];
        this.$set(array, i, array[randomIndex]);
        this.$set(array, randomIndex, tempVal);
      }
    }
    
  }
});
Run Code Online (Sandbox Code Playgroud)

这是一个工作小提琴