1

我在 Vue.JS 上苦苦挣扎,该组件具有作为子项/插槽的一些带有画布数据的“复杂”组件(例如地图)。

我想避免当父组件重新渲染时,它们的内部插槽重新渲染。由于这些组件的工作方式(或任何其他场景),每次重新渲染时都需要执行所有“加载”步骤。即使保存他们的实时状态。

例如:

组件.vue

<template>
    <div>
        <span>{{value}}</span>
        <slot></slot>
    </div>
</template>

看法

<Component v-model="value">
    <Map :latitude="0" :longitude="0"/>
</Component>

<script>
    this.value = "Hello";
    setTimeout(()=>{
        this.value="Hello world!";
    },1000);
</script>

有什么方法可以防止插槽在其父级重新渲染时重新渲染?

提前致谢。

4

1 回答 1

0

你好为子组件使用道具,这个子组件不会重新渲染

应用程序

<template>
  <div id="app">
    <HelloWorld msg="Hello Vue in CodeSandbox!" :somedata="key">
      slot information key: {{ key }}
    </HelloWorld>

    <button @click="key++">key++</button>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld,
  },
  data() {
    return {
      key: 0,
    };
  },
};
</script>

孩子

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h3>somedata from props: {{ somedata }}</h3>
    <hr />
    <slot></slot>
    <hr />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: {
      type: String,
      default: "",
    },
    somedata: {
      type: Number,
      default: 999,
    },
  },
  created() {
    console.log("renred");
  },
};
</script>

怎么看我console.log("renred");在子组件中使用的,可以在控制台查看,信息只会显示一次。

https://codesandbox.io/s/naughty-platform-ib68g?file=/src/components/HelloWorld.vue

于 2020-11-30T19:20:31.357 回答