【发布时间】:2018-12-16 05:40:51
【问题描述】:
我正在尝试在 vue.js 中创建一个 shuffle 函数。所以,为此我创建了一个计算属性,然后我调用了一个方法。但它不起作用。我已经创建了另外两个函数“添加”和“删除”这两个工作正常,除了“随机播放”。
抛出错误: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)
}
}
});
.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
}
<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>
【问题讨论】:
-
您不能将计算属性调用为函数。它们是属性 (vuejs.org/v2/guide/computed.html) 。如果你想要一个函数将它移到方法中,你可以这样调用它。
-
我看不出
moveIndex作为计算值有意义的单一原因。将其放入方法中。 -
这也是x-y problem的经典案例。
标签: vue.js computed-properties