Vue 知识点

Vue中比较常用的知识点汇总

1. Vue 中 provide 和 inject 总结

这两个属性是要配套使用 成对出现的 , 他们的作用是 在父组件中声明 provide属性,那么他的所有子组件(包括孙组件 只要和这个组件有直接或者间接的联系) 都可以通过 inject属性来获取 provide中声明的属性

如果想要顶级父组件(声明provide的组件) 和所有子组件或孙组件实现数据联动, 那么 顶级父组件必须(声明provide的组件)在provide中声明的数据是一个Object类型 其他什么数据类型都不好使 , 子组件或孙组件 inject接收的

Vue代码

父组件代码
<template>
  <div ckass="tops">
    <div>
      父组件的:
      <el-input v-model="testProvide.name"></el-input>
    </div>
    <div class="dashboard-editor-container">
      <ChildrenComponent>
      </ChildrenComponent>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import ChildrenComponent from '引入子组件地址'

  export default {
    name: "ParentComponent",
    components:{
		ChildrenComponent 
    },
    data() {
      return {
      	// 这里的 testProvide 是一个对象类型的 
        testProvide: {
          name:'Hello parent'
        },
      }
    },
    provide(){
      return{
      	// 在 provide 中声明一个 testInject的对象 其值是testProvide对象
        testInject: this.testProvide
      }
    },
  }
</script>
子组件代码
<template>
  <div>
      <div>
        子组件的:
        <el-input v-model="testInject.name"></el-input>
      </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
      };
    },
    inject:{
      testInject:{},
    },
结果

在这里插入图片描述
在这里插入图片描述

子组件输入的值会改变父组件的值 , 父组件输入的值会改变子组件的值

2. Vue 在父组件中销毁子组件 , 简易版

  • 1.代码
	<el-dialog title="生成报价单" :visible.sync="showGenericPriceTableDialog" width="1450px" 
	   :close-on-click-modal="false" 
	   :close-on-press-escape="false"
	   :destroy-on-close="true"
	   :before-close="beforeClosePriceTable"
	   append-to-body center >
	
	      <div style="border: 2px solid;padding:30px 60px">
	         <PriceTableTemplate
	            v-if="showGenericPriceTableDialog"
	            ref="priceTableTemplate"
	            :priceTableData="translatePriceTableData"
	         >
	         </PriceTableTemplate>
	      </div>
	
	      <div slot="footer" class="dialog-footer">
	         <el-button type="danger" @click="closeGenericPriceDialog">关闭报价单</el-button>
	      </div>
	   </el-dialog>
         // 关闭构建一次性报价单的页面
      closeOncePriceTableDialog(){
         this.showOncePriceTableDialog = false;
      },

      // Vue 销毁实例直接 v-if 来判断
      beforeClosePriceTable(){
         this.showOncePriceTableDialog = false;
      },
  • 2.应用

使用ElementUi 时 点击 生成报价单 this.showGenericPriceTableDialog = true dialog会显示 , 而dialog里边嵌套了一个报价单组件 , 并且把当前父组件中的值 translatePriceTableData 传递到子组件中去了 , 但是执行关闭
父组件 的dialog操作时 子组件已经应用到 传递过去的值时 会报错未找到字段值

  • 3. 解决方案

当执行dialog 的关闭方法时 先调用dialog的 before-close 钩子函数 , 使用 v-if 来先结束关闭子组件的生命周期 , 就不会报错了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值