步骤一: 安装echarts

yarn add echarts -S

npm i ecahrts -S

步骤二:引入方式

1. Es6 import 方式

<template>

  <div class="hello">
    <div id="myEchart" ref="myEchart" style="width: 200px;height:200px" ></div>
  </div>
</template>
<script setup>
  import { ref, reactive, defineExpose, watch, onMounted, 		 inject } from 'vue'
  import * as echarts from 'echarts'
 onMounted(() => {
  console.log('this:' + this)
  arry1.value.push('a')
  const myEchartDiv = document.getElementById('myEchart')
  const myEchart = echarts.init(myEchartDiv)
  // 绘制图表
  myEchart.setOption({
    title: {
      text: 'ECharts 入门示例2'
    },
    tooltip: {},
    xAxis: {
      data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20]
      }
    ]
  })
})
  <script/>
  1. Node.js require() 引入
<template>

 <div class="hello">
   <div id="myEchart" ref="myEchart" style="width: 200px;height:200px" ></div>
 </div>
</template>
<script setup>
 import { ref, reactive, defineExpose, watch, onMounted, 		 inject } from 'vue'
onMounted(() => {
 console.log('this:' + this)
 arry1.value.push('a')
 const myEchartDiv = document.getElementById('myEchart')
 const myEchart = echarts.init(myEchartDiv)
 // 绘制图表
 myEchart.setOption({
   title: {
     text: 'ECharts 入门示例2'
   },
   tooltip: {},
   xAxis: {
     data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
   },
   yAxis: {},
   series: [
     {
       name: '销量',
       type: 'bar',
       data: [5, 20, 36, 10, 10, 20]
     }
   ]
 })
})
 <script/>
  1. App.vue 下 provide() ,子组件下 inject() 方式
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view/>
</template>

<script setup>
import * as echarts from 'echarts'
import { provide } from 'vue'
provide('echart', echarts)

</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

不能采用的方式

不能采用全局挂载,this 调用的方式,因为
根据官方解释 Vue3官网

在 setup() 内部,this 不是该活跃实例的引用,因为 setup() 是在解析其它组件选项之前被调用的,所以 setup()
内部的 this 的行为与其它选项中的 this 完全不同。这使得 setup() 在和其它选项式 API 一起使用时可能会导致混淆。

也就是: setup并没有通过各种方式去绑定this
在vue2中,我们可以在optionsApi中调用this来指向当前组件的实例,但是在vue3的setup中并不能这样做,因为setup位于组件创建成功后但是并没有解析data、computed、methods中间,所以他们无法从setup中调用this去获得
参考博文

Logo

前往低代码交流专区

更多推荐