【问题标题】:Why don't changes to my prop update the dom?为什么不更改我的道具更新 dom?
【发布时间】:2017-09-28 15:26:06
【问题描述】:

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。

但是当我删除时,prop 的内部状态发生了变化,但是 dom 没有更新。

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

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

    当您将 javascript 对象添加到数据时,Vue 会将其转换为 观察到的 值。当您传递一个内联数组时,正如您在问题中的代码中所做的那样,该数组是 not 观察到的,并且 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>

    【讨论】:

    • 这实际上回避了问题,将数据包含在 Vue 组件中。前提是数据来自其他地方,需要交给组件。所以我需要以某种方式将道具复制到组件数据中?
    • @DavidYell 然而,这并不是真正的问题。您要么需要使数据反应,要么强制 DOM 更新。 jsfiddle.net/3zn9arj3/6
    • 我已经设法通过将对象复制到 created 方法中的数据来使其工作。
    • 当然,也有很多方法可以做到这一点。 jsfiddle.net/3zn9arj3/8
    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 2021-08-20
    • 2016-12-17
    • 2015-03-15
    • 2020-04-30
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多