Vue.js vuex 道具不重新渲染

Vue.js vuex props don't rerender

我正在使用 Vuex 并显示如下数据:

<template>
    <div>
        <div>
            <div v-for="port in ports">
                <port :port="port"></port>
            </div>
        </div>
    </div>
</template>

<script>
    import { mapState } from 'vuex';

    export default {
        computed: {
            ...mapState({
                ports: state => state.ports.ports,
            })
        }
    }
</script>

我现在遇到的问题是,当我更改另一个组件中的 ports state 时,它会正确更新 ports statev-for 循环中的端口未更新。

如何确保端口组件 rerenders 中的数据也正确?

Vue Beginner Gotchas: Why isn't the DOM updating?

Most of the time, when you change a Vue instance’s data, the view updates. But there are two edge cases:

  1. When you are adding a new property that wasn’t present when the data was observed.

  2. When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property.

如果您通过执行以下操作来更改端口数据:

this.ports[0] = 1234;

或者像这样:

this.ports[4].property = 'some value';

然后 Vue 将无法检测到发生了更改。你可以通过以下方式绕过这个陷阱:

Vue.set(this.ports, 0, 1234);