我在尝试从 Vue 1.0.27 迁移到 Vue 2.0.1 时遇到以下问题。
编辑添加了工作JSFidle
情况:
我构建了一个非常简单的应用程序,它获取任务列表(来自模型)并将它们显示在无序列表中,以及未标记为已完成的任务数量(即剩余任务)。ViewModel 和 Model 的代码如下所示:
/*************
* ViewModel *
* ***********/
var vm = new Vue({
el: '#my-app',
data: data
});
/*************
* Model *
* ***********/
var data = {
my_tasks: [
{body: "Go to the doctor", completed: false},
{body: "Go to the bank", completed: false},
{body: "Go to the zoo", completed: false}
],
};
为了显示任务列表,我使用了<task-list>
自定义组件。组件:
- 通过props拥有一个
tasks
属性 - 有一个名为的计算属性
remaining
,用于计算未完成的任务数 - 有两种方法
toggleCompletedStatus
和inProgress
自定义组件的代码如下所示
/*****************
* Component *
* ***************/
Vue.component('task-list', {
template: '#task-list-template',
props: ['tasks'],
computed: {
remaining: function () {
return this.tasks.filter(
this.inProgress
).length;
}
},
methods: {
/**
* Toggle the completed status of a task
* @param item
*/
toggleCompletedStatus: function (item) {
return item.completed = !item.completed;
},
/**
* Returns true when task is in progress (not completed)
* @param item
*/
inProgress: function (item) {
return !item.completed;
}
},
});
<template id="task-list-template">
<div>
<h3>My tasks list ( {{ remaining }} )</h3>
<ul>
<li v-for="task in tasks" @click="toggleCompletedStatus(task)">
{{ task.body }}
</li>
</ul>
</div>
</template>
最后,在我看来,我使用v-bind
指令将组件的任务属性与数据绑定。
/************
* View * <-- works fine with both Vue 1.X and 2.x
* **********/
div id="my-app">
<task-list :tasks="my_tasks"></task-list>
</div>
问题:
如果我尝试内联传递任务列表,则remaining
当用户单击任务时,计算属性不会更新。(即当 task.completed 属性发生变化时)
/************
* View * <-- works in Vue 1.x, NOT working with Vue 2.x
* **********/
div id="my-app">
<task-list :tasks="[{body: "Go to the doctor", completed: false}, {body: "Go to the bank", completed: false}, {body: "Go to the dentist", completed: false}]"></task-list>
</div>
如果我尝试从服务器传递数据,也会存在同样的问题。以下示例在后端使用 Laravel 5.3:
/************
* View * <-- works in Vue 1.x, NOT working with Vue 2.x
* **********/
div id="my-app">
<task-list :tasks="{{$tasks}}"></task-list> <!-- {{$tasks}} are the json encoded data from the server -->
</div>
任何帮助表示赞赏