先安装echarts:npm install echarts --save
// echarts.vue文件:
(Vue重点:
(1)created的时候才能拿到data中的数据;
(2)mounted的时候才能拿到页面中的DOM元素!
(3).vue文件中的this是VueComponent对象.
)
<template>
<div>
<h2>echarts图表</h2>
<div class="box" ref="box">
</div>
</div>
</template>
<script>
import echarts from "echarts"
export default {
data(){
return{
msg:"data中的数据"
}
},
beforeCreate(){
console.log(1,this.msg,this.$refs.box); //1 undefined undefined
},
created(){
console.log(2,this.msg,this.$refs.box); //2 "data中的数据" undefined
},
beforeMount(){
console.log(3,this.msg,this.$refs.box); //3 "data中的数据" undefined
},
mounted(){
// console.log(4,this.msg,this.$refs.box) //4 "data中的数据" <div data-v-80daac0c class="box"></div>
// 基于准备好的dom,初始化echarts实例
this.myChart = echarts.init(this.$refs.box);
// 指定图表的配置项和数据
this.option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
this.myChart.setOption(this.option);
}
}
</script>
<style scoped>
.box{
width:200px;
/* height:200px; */
}
</style>
其他扩展:
(1).vue文件(内部已经使用了严格模式,匿名自执行函数中this指向undefined)中通过var声明的变量,不会自动绑定到window对象和VueComponent对象上!
(2)普通.js文件(没有使用严格模式的,匿名自执行函数中this指向window)中通过var声明的变量,会自动绑定到window对象上。
// XX.vue文件中
mounted(){
//在.vue文件中通过var声明的变量,不会自动绑定到window对象和组件内的this对象上!
var ji="我是var的变量";
console.log(window.hasOwnProperty("ji")); //false
console.log(this.hasOwnProperty("ji"));//false
// 判断某个对象是否含有某个属性:
var obj={a:1};
console.log(obj.hasOwnProperty("a")) //true
// .vue文件中的this是指VueComponent对象。
console.log(this); //对象VueComponent {_uid: 7, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
console.log(Object.prototype.toString.call(this)); //[object Object]
//自执行匿名函数(可判断一个文件中是否使用了严格模式,严格模式下this为undefined;非严格
模式下this为window对象)。
// .vue中自执行匿名函数调用的上下文是 undefined(.vue文件中使用了严格模式)。
var strict=(function(){
console.log(22,this); //22 undefined
return this
})();
console.log("函数调用的上下文",strict); //函数调用的上下文 undefined
},
// XXX.html文件中(普通js文件,没有使用严格模式,全局环境下声明的变量默认自动会绑定到window对象上)
<script>
var strict2=(function(){
console.log(1,this); //1 Window {parent: Window, postMessage: ƒ, blur: ƒ, focus:
ƒ, close: ƒ, …}
return this;
})();
console.log(window.hasOwnProperty("strict2")); // true
console.log(strict2); // Window
</script>