【问题标题】:How to render child components in parent component in vue.js and only render the changes occurred in child component?如何在 vue.js 中渲染父组件中的子组件,并且只渲染子组件中发生的更改?
【发布时间】:2019-10-30 15:28:28
【问题描述】:

到目前为止,我所做的是创建了两个组件,它们存在于 src/components 文件夹中,我想添加这些组件,它们包含在 src/views 文件夹中的父组件中。

我有一个名为 form.vue 的组件和另一个名为 background.vue的组件

我想要的是,在backgound.vue(用于背景)之上显示form.vue(包含一个表单)。所以每次,孩子发生任何变化,都会迫使整个父页面重新渲染。那么有什么办法可以解决这个问题吗?

以下是文件夹结构:

【问题讨论】:

    标签: vuejs2 vue-component parent-child


    【解决方案1】:

    您可以为此使用slots,因此在您的 background.vue 中您将拥有:

    <template>
     ...
       <slot><slot> <!-- place where the external component will be rendered -->
     ...
     </template>
    

    然后在主要组件中,您将拥有:

    <background>
      <my-form></my-form>
    </background>
    

    【讨论】:

    • 您好 Florentin,感谢您的回复,但我不明白以下 3 行
    • @Dcoder 你好,你是说&lt;background&gt; &lt;my-form&gt;&lt;/my-form&gt;&lt;/background&gt;?这就是您将要在其中使用背景和表单的页面组件 (page1.vue) 中的内容。
    【解决方案2】:

    创建 3 个组件并将其中的 2 个调用到第 3 个组件中。

    例如:

    You have
    component1.vue
    component2.vue
    component3.vue
    

    在component3.vue中:

    <script>
        //import components
        import componentOne from '/path/to/component1'
        import componentTwo from '/path/to/component2'
        //now register them locally to use them in this component
        export default{
            components:{componentOne, componentTwo}
    
        }
       //now call these components in <template> section using kebab case
       <template>
         <div>
              <component-one />  //camelCAse name of component in <script> tag  is used in kebab case in template section
              <component-two />  // means componentTwo will called as <component-two/>
         </div>     
       </template>
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 2020-01-20
      • 2021-12-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2019-06-01
      相关资源
      最近更新 更多