vue3.0(SFC(<script setup>))+Sass+TypeScript使用&報錯記錄&解決方案(持續記錄,保持關注)

一、vue2.0通過echarts初始化dom實例的時候要使用this.$refs.domEle, 但是3.0發生了改變,需要在setup定義一個字段,在dom元素標簽里定義跟setup里聲明的變量同名的ref屬性值,e.g: <div id="ryCharts" ref="chartDom" class="bcontent"></div>

<script setup lang="ts">
const chartDom = ref<HTMLElement | null>(null);
let myChart = echarts.init(chartDom.value); //這行代碼會有ts驗證的報錯,但是不影響正常運行
</script>

報錯信息如下:

    Argument of type 'HTMLElement | null' is not assignable to parameter of type 'HTMLElement'.
Type 'null' is not assignable to type 'HTMLElement'.

解決方案如下:

<script setup lang="ts">
  const chartDom = ref<HTMLElement | ''>('');
  let myChart = echarts.init(chartDom.value as HTMLElement); 
  //通過console會發現chartDom.value其實跟之前this.$refs.domEle拿到的值是一樣的,都是元素信息;
  //ts是js的超集,它會驗證數據格式,所以需要為它設置類型 HTMLElement.
</script>

二、子組件可以通過getCurrentInstance()獲取父組件里的數據

//import
import { onMounted, getCurrentInstance } from 'vue'

//use 
const currentInstance = getCurrentInstance()

onMounted(() => {
  console.log(currentInstance?.parent)
})

三、事件總線(用于非父子組件通信):事件總線模式可以被替換為使用外部的、實現了事件觸發器接口的庫例如 mitttiny-emitter,這里使用tiny-emitter
1.install(下載)

npm install --save tiny-emitter

2.usage(使用)

// for js 
  const emitter = require('tiny-emitter/instance')

//接收事件
emitter.on('some-event', function (arg1, arg2, arg3) {
 //
});

//發送事件
emitter.emit('some-event', 'arg1 value', 'arg2 value', 'arg3 value');

參考鏈接:1. vue3.X遷移策略

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容