为什么不改变我的道具更新dom?

时间:2017-09-28 15:26:06

标签: vue.js vuejs2

TL; DR小提琴,https://jsfiddle.net/neon1024/3zn9arj3/4/

<div id="app">
    <repos v-bind:repos='[{id: 1, full_name: "davidyell/app", description: "Daves custom CakePHP 3.0 app template"}, {id: 2, full_name: "davidyell/app-template", description: "An empty 2.4 cakephp application template, for use with composer"}]'></repos>
</div>
Vue.component('repos', {
    template: `
      <div>
        <ul>
            <li v-for="(repo, index) in repos">
                {{ repo.full_name }} -> {{ repo.description }}
                <span v-on:click="removeIt" style="color:red;cursor:pointer" v-bind:data-index="index">Delete</span>
            </li>
        </ul>
      </div>
  `,
    props: {
        repos: {
            required: true
        }
    },
    methods: {
        removeIt(event) {
            this.repos.splice(event.target.dataset.index, 1);
            console.log(this.repos);
        }
    }
});

new Vue({
    el: '#app'
});

我使用道具将数据传递到我的组件中,我希望能够删除项目并更新dom。

但是当我删除时,道具的内部状态会发生变化,但dom不会更新。

1 个答案:

答案 0 :(得分:0)

您将静态(非反应)数组传递给组件。您需要将数组添加到数据中以使其具有反应性。

当您向数据添加javascript对象时,Vue会将其转换为观察到的值。当您传递内联数组时,就像在问题中的代码中一样,数组被观察到,并且Vue不知道更新DOM。

Vue.component('repos', {
    template: `
      <div>
        <ul>
            <li v-for="(repo, index) in repos">
                {{ repo.full_name }} -> {{ repo.description }}
                <span v-on:click="removeIt" style="color:red;cursor:pointer" v-bind:data-index="index">Delete</span>
            </li>
        </ul>
      </div>
  `,
    props: {
        repos: {
            required: true
        }
    },
    methods: {
    	removeIt(event) {
			this.repos.splice(event.target.dataset.index, 1);
            console.log(this.repos);
        }
    }
});

new Vue({
    el: '#app',
    data:{
      repos: [{id: 1, full_name: "davidyell/app", description: "Daves custom CakePHP 3.0 app template"}, {id: 2, full_name: "davidyell/app-template", description: "An empty 2.4 cakephp application template, for use with composer"}]
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
    <repos v-bind:repos='repos'></repos>
</div>