The technology stack in the internship program is iView+Vue+Echarts, packaged with Webpack and so on. Now record the learning and review summary, and then file it.
Vue
Before getting to know iView, understand the basics of Vue.
Vue (pronounced vju/curliest, similar to View) is a set of progressive frameworks for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.
Vue common commands
v-bind
Align the title property of the element node with the Message property of the Vue instance
<div id="app-2">
<span v-bind:title="message">Hover for a few seconds to see the prompt for dynamic binding here!</span>
</div>
Copy the code
var app2 = new Vue({
el: '#app-2'.data: {
message: 'Page loaded on' + new Date().toLocaleString()
}
})
Copy the code
Abbreviations:
<! -- Complete syntax -->
<a v-bind:href="url">.</a>
<! - for - >
<a :href="url">.</a>
Copy the code
v-if
Controls whether to toggle an element to display
<div id="app-3">
<p v-if="seen">Now you see me</p>
</div>
Copy the code
var app3 = new Vue({
el: '#app-3'.data: {
seen: true}})Copy the code
v-for
Bind an array of data to render a list of items
<div id="app-4">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>
Copy the code
var app4 = new Vue({
el: '#app-4'.data: {
todos: [{text: 'learning JavaScript' },
{ text: 'learning Vue' },
{ text: 'The whole cattle Project'}]}})Copy the code
v-on
Add an event listener through which to invoke methods defined in the Vue instance
<div id="app-5">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Inversion of the message</button>
</div>
Copy the code
var app5 = new Vue({
el: '#app-5'.data: {
message: 'Hello Vue.js! '
},
methods: {
reverseMessage: function () {
this.message = this.message.split(' ').reverse().join(' ')}}})Copy the code
Abbreviations:
<! -- Complete syntax -->
<a v-on:click="doSomething">.</a>
<! - for - >
<a @click="doSomething">.</a>
Copy the code
v-model
Easy two-way binding between form input and application state
<div id="app-6">
<p>{{ message }}</p>
<input v-model="message">
</div>
Copy the code
var app6 = new Vue({
el: '#app-6'.data: {
message: 'Hello Vue! '}})Copy the code
Componentized application building
A component is essentially a Vue instance with predefined options.
<div id="app-7">
<ol>
<! -- Now we provide todo objects for each Todo-Item. Todo objects are variables, i.e. their contents can be dynamic. We also need to provide a "key" for each component, more on that later. -->
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id"
></todo-item>
</ol>
</div>
Copy the code
Vue.component('todo-item', {
props: ['todo'].template: '<li>{{ todo.text }}</li>'
})
var app7 = new Vue({
el: '#app-7'.data: {
groceryList: [{id: 0.text: 'vegetables' },
{ id: 1.text: "Cheese" },
{ id: 2.text: 'Whatever other people eat.'}]}})Copy the code
We’ve managed to split the application into two smaller units. The sub-unit is well decoupled from the parent unit through the PROP interface. We can now further improve the
component to provide more complex templates and logic without affecting the parent unit.
Vue special features
ref
Expectation: string
Ref is used to register reference information for an element or child component. The reference information will be registered with the parent component’s $refs object. If used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference refers to the component instance
<! -- `vm.$refs.p` will be the DOM node -->
<p ref="p">hello</p>
<! -- `vm.$refs.child` will be the child component instance -->
<child-component ref="child"></child-component>
Copy the code
// Get the DOM element
this.$refs.p
Copy the code
vm.$refs
Type: the Object
An object that holds all DOM elements and component instances for which the REF feature is registered.
Vue evaluates attributes
Expressions in templates are very convenient, but they are designed for simple calculations. Putting too much logic into a template can make it too heavy and difficult to maintain. For any complex logic, you should use computed property computed.
Based on example
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
Copy the code
var vm = new Vue({
el: '#example'.data: {
message: 'Hello'
},
computed: {
// Calculates the getter for the property
reversedMessage: function () {
// 'this' points to the VM instance
return this.message.split(' ').reverse().join(' ')}}})Copy the code
Here we declare a calculated property reversedMessage. The function we provide will be used as the getter for the attribute vm.reversedMessage:
console.log(vm.reversedMessage) // => 'olleH'
vm.message = 'Goodbye'
console.log(vm.reversedMessage) // => 'eybdooG'
Copy the code
Calculate the property cache vs method
You may have noticed that we can achieve the same effect by calling methods in expressions:
<p>Reversed message: "{{ reversedMessage() }}"</p>
Copy the code
// In the component
methods: {
reversedMessage: function () {
return this.message.split(' ').reverse().join(' ')}}Copy the code
We can define the same function as a method rather than a calculated property. The end result is exactly the same. The difference, however, is that computed attributes are cached based on their reactive dependencies. They are reevaluated only when the associated reactive dependencies change. This means that as long as the Message has not changed, multiple visits to the reversedMessage computed property will immediately return the previous computed result without having to execute the function again. By contrast, the calling method will always execute the function again whenever a rerender is triggered.
Compute properties vs. listen properties
Vue provides a more general way to observe and respond to changes in data on Vue instances: listening properties. However, it is often better to use computed properties rather than imperative Watch callbacks. The listener approach is most useful when asynchronous or expensive operations need to be performed when data changes.
Here’s an example
<div id="demo">{{ fullName }}</div>
Copy the code
var vm = new Vue({
el: '#demo'.data: {
firstName: 'Foo'.lastName: 'Bar'.fullName: 'Foo Bar'
},
watch: {
firstName: function (val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + ' ' + val
}
}
})
Copy the code
The code above is imperative and repetitive. Compare this to the version of the calculated property:
var vm = new Vue({
el: '#demo'.data: {
firstName: 'Foo'.lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
Copy the code
Vue components
A component is a reusable Vue instance that can be used as a custom element in a Vue root instance created with New Vue.
The Vue component has three elements
- Each component carries a name. Under the case
button-counter
Is the name of the component.
<div id="components-demo">
<button-counter></button-counter>
</div>
Copy the code
- Register component: The format of the component is
Vue.component('component-name',{});
. This is global registration.
Components receive the same options as new Vue, such as Data, computed, Watch, Methods, and lifecycle hooks.
In components, data must be a function, so each instance can maintain a separate copy of the returned object to achieve component reusability.
// Define a new component called button-counter
Vue.component('button-counter', {
data: function () { // The component's data must be a function
return {
count: 0}},template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>' // The HTML display of the component
})
Copy the code
- use
new Vue
The Vue root instance must be created after the component is registered.
new Vue({ el: '#components-demo' }) // The mount point here is the parent element of the component
Copy the code
PS: Note that steps 2 and 3 cannot be exchanged.
Pass data to child components through Prop
A Prop is a set of custom features you can register on a component. When a value is passed to a prop feature, it becomes a property of that component instance.
By default, a component can have any number of props, and any value can be passed to any prop.
You’ll find that we can use V-bind to pass prop dynamically.
<div id="father">
<blog-post v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post" // v-bindThe dynamic transferprop
></blog-post>
</div>
Copy the code
Vue.component('blog-post', {
props: ['post']./ / register prop
template: `
{{ post.title}}
`
})
new Vue({
el: '#father'.data: {
posts: [ // Properties of each prop are automatically available in blog-post
{id: 1.title: 'title1'.content: 'content1'},
{id: 2.title: 'title2'.content: 'content2'}]}})Copy the code
The above v-bind:post=”post” is to pass all properties of the object as prop, equivalent to
v-bind:id="post.id"
v-bind:title="post.title"
v-bind:content="post.content"
Copy the code
Any type of value can be passed to a prop, such as numbers, booleans, arrays, objects, etc.
Prop type
Can be:
props: ['title'.'likes'.'isPublished'.'commentIds'.'author']
Copy the code
However, in general you want each prop to have a specified value type. In this case, you can list the prop as an object. The names and values of these properties are the names and types of the prop:
props: {
title: String.// Prop name is title and type is String
likes: Number.isPublished: Boolean.commentIds: Array.author: Object.callback: Function.contactsPromise: Promise // or any other constructor
}
Copy the code
Single data flow for PROP
All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand.
Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console.
Listen for child component events
The parent component can listen for any event of a child component instance via V-ON just as it handles native DOM events. The child component can fire an event by calling the built-in $emit method and passing in the event name.
We added a button before the body of each post to enlarge the size:
<div id="blog-posts-events-demo"> <div v-bind:style="{ fontSize: postFontSize + 'em' }"> <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" <! V-on :enlarge-text="postFontSize += 0.1" ></blog-post> </div> </div>Copy the code
Vue.component('blog-post', {
props: ['post'].template: ` <div class="blog-post"> <h3>{{ post.title }}</h3> <! A child component can trigger an event by calling the built-in $emit method and passing in the event name --> <button V-on :click="$emit('enlarge-text')"> enlarge text </button> <div v-html="post.content"></div> </div> `
})
new Vue({
el: '#blog-posts-events-demo'.data: {
posts: [{id: 1.title: 'title1'.content: 'content1'},
{id: 2.title: 'title2'.content: 'content2'}].postFontSize: 1 / / initialization}})Copy the code
Throw a value using an event
Sometimes it’s useful to have an event that throws a specific value. For example, we might want the component to decide how much larger its text should be. The second argument to $emit can then be used to provide this value:
<button v-on:click="$emit (' enlarge - text, 0.1)">
Enlarge text
</button>
Copy the code
Then when the parent component listens for this event, we can access the value thrown by $event:
<blog-post
.
v-on:enlarge-text="postFontSize += $event"
></blog-post>
Copy the code
Used on componentsv-model
Custom events can also be used to create custom input components that support V-Models.
<div id="father">
<custom-input v-model="searchText"></custom-input>
</div>
Copy the code
In order for it to work, the inside this component must:
Bind its value feature to a prop named Value that throws a new value through a custom input event when its input event is raised
Vue.component('custom-input', {
props: ['value'].template: ` `
})
new Vue({
el: '#father'
})
Copy the code
The component registration
Global registration
The three components mentioned earlier are the global registration method. Components can be used in the template of any newly created Vue root instance (New Vue) after registration.
Such as
<div id="app">
<component-a></component-a>
<component-b></component-b>
<component-c></component-c>
</div>
Copy the code
Vue.component('component-a', { / *... * / })
Vue.component('component-b', { / *... * / })
Vue.component('component-c', { / *... * / })
new Vue({ el: '#app' })
Copy the code
Local registration
Global registration is often not ideal, often resulting in unnecessary increase in js downloads by users.
Components can be defined using a plain JS object:
var ComponentA = { / *... * / }
var ComponentB = { / *... * / }
var ComponentC = { / *... * / }
// Then define the component you want to use in the Components option:
new Vue({
el: '#app'.components: {
'component-a': ComponentA,
'component-b': ComponentB
}
})
Copy the code
<div id="father">
<component-a></component-a>
<component-b></component-b>
</div>
Copy the code
For each attribute in the Components object, the attribute name is the name of the custom element, and the attribute value is the component’s option object.
A locally registered component is not available in its children
For ComponentA to be available in ComponentB, you need the following rewrite:
var ComponentA = { / *... * / }
var ComponentB = {
components: {
'component-a': ComponentA
},
// ...
}
Copy the code
If you use the ES2015 module with Babel and Webpack, the code looks more like:
import ComponentA from './ComponentA.vue'
export default {
components: {
ComponentA
},
// ...
}
Copy the code
Note that in ES2015+, the variable name for ComponentA is ComponentA: ComponentA.
- The name of the custom element used in the template
- The variable name that contains the component option
Local registration in the module system
If you are using a modular system such as Webpack, it is recommended to create a Components directory and place each component in its own file.
Then import each file you want to use before local registration. For example, in a hypothetical ComponentB.js or ComponentB.vue file:
import ComponentA from './ComponentA'
import ComponentC from './ComponentC'
export default {
components: {
ComponentA,
ComponentC
},
// ...
}
Copy the code
ComponentA and ComponentC are now available for use in ComponentB templates.
Automated global registration of the underlying components
Basic components are relatively generic elements such as input fields or buttons that are frequently used within components.
If you use Webpack (or Vue CLI 3+ for Webpack internally), you can use require.context to register only these very generic base components globally. Here’s a sample code that lets you import the underlying components globally in an application entry file (such as SRC /main.js) :
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
const requireComponent = require.context(
// The relative path of its component directory
'./components'.// Whether to query the subdirectory
false.// A regular expression that matches the underlying component file name
/Base[A-Z]\w+\.(vue|js)$/
)
requireComponent.keys().forEach(fileName= > {
// Get the component configuration
const componentConfig = requireComponent(fileName)
// Get the PascalCase name of the component
const componentName = upperFirst(
camelCase(
// Get a file name independent of directory depth
fileName
.split('/')
.pop()
.replace(/\.\w+$/.' ')))// Globally register components
Vue.component(
componentName,
// If the component option is exported via 'export default',
// Then '.default 'is preferred,
// Otherwise fall back to the root of the use module.
componentConfig.default || componentConfig
)
})
Copy the code
inner
Deep into the responsivity principle
iView
component
Select the drop-down box
<Select v-model="allouseModel" style="width:100px">
<Option v-for="item in allouseList" :value="item.value" :key="item.value">{{ item.label }}</Option>
</Select>
Copy the code
allouseList : [
{
value: 'allo'.label : 'Distribution rate'
},
{
value: 'use'.label : 'Utilization'}].allouseModel : 'allo'.Copy the code
Label Is used for initialization only in remote mode. You need to manually set the label of an option because only value can be used to determine the label.
The checkbox boxes,
Use a combination of<template>
<CheckboxGroup v-model="social">
<Checkbox label="twitter">
<Icon type="social-twitter"></Icon>
<span>Twitter</span>
</Checkbox>
<Checkbox label="facebook">
<Icon type="social-facebook"></Icon>
<span>Facebook</span>
</Checkbox>
<Checkbox label="github">
<Icon type="social-github"></Icon>
<span>Github</span>
</Checkbox>
<Checkbox label="snapchat">
<Icon type="social-snapchat"></Icon>
<span>Snapchat</span>
</Checkbox>
</CheckboxGroup>
<CheckboxGroup v-model="fruit">
<Checkbox label="Banana"></Checkbox>
<Checkbox label=The word "apple"></Checkbox>
<Checkbox label="Watermelon"></Checkbox>
</CheckboxGroup>
</template>
<script>
export default {
data () {
return {
social: ['facebook'.'github'].fruit: ['apple']}}}</script>
Copy the code
Menu Navigation Menu
<template>
<Menu mode="horizontal" :theme="theme1" active-name="1">
<MenuItem name="1">
<Icon type="ios-paper"></Icon>Content management</MenuItem>
<MenuItem name="2">
<Icon type="ios-people"></Icon>User management</MenuItem>
<Submenu name="3">
<template slot="title">
<Icon type="stats-bars"></Icon>Statistical analysis</template>
<MenuGroup title="Use">
<MenuItem name="3-1">Add and start</MenuItem>
<MenuItem name="3-2">Active analysis</MenuItem>
<MenuItem name="3-3">During analysis</MenuItem>
</MenuGroup>
<MenuGroup title="Retained">
<MenuItem name="3-4">Users of retained</MenuItem>
<MenuItem name="3-5">Loss of users</MenuItem>
</MenuGroup>
</Submenu>
<MenuItem name="4">
<Icon type="settings"></Icon>Comprehensive set</MenuItem>
</Menu>
<br>
<p>Change theme</p>
<RadioGroup v-model="theme1">
<Radio label="light"></Radio>
<Radio label="dark"></Radio>
<Radio label="primary"></Radio>
</RadioGroup>
</template>
<script>
export default {
data () {
return {
theme1: 'light'}}}</script>
Copy the code
Echarts
charts
Histogram bar
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<! Echarts.js -->
<script src="echarts.min.js"></script>
</head>
<body>
<! -- Prepare a Dom with size (width and height) for ECharts
<div id="main" style="width: 600px; height:400px;"></div>
<script type="text/javascript">
// Initializes the echarts instance based on the prepared DOM
var myChart = echarts.init(document.getElementById('main'));
// Specify the chart configuration items and data
var option = {
title: {
text: 'Getting started with ECharts'
},
tooltip: {},
legend: {
data: ['sales']},xAxis: {
data: ["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"]},yAxis: {},
series: [{
name: 'sales'.type: 'bar'.data: [5.20.36.10.10.20]]}};// Display the chart using the configuration items and data you just specified.
myChart.setOption(option);
</script>
</body>
</html>
Copy the code
Pie pie
Pie charts have only one dimensional values and do not require categories. It’s not in rectangular coordinates, and you don’t need xAxis,yAxis.
myChart.setOption({
series: [{name: 'Access source'.type: 'pie'.radius: '55%'.data:[
{value:235.name:'Video advertising'},
{value:274.name:'Affiliate advertising'},
{value:310.name:'Email marketing'},
{value:335.name:'Direct access'},
{value:400.name:'Search engines'}]}]})Copy the code
Personalized style
ECharts has some common styles, such as shadow, transparency, color, border color, border width, etc. These styles are generally set in the itemStyle of the series. For example, set the color of the sector:
itemStyle: {
// Set the color of the sector
color: '#c23531'.shadowBlur: 200.shadowColor: 'rgba (0, 0, 0, 0.5)'
}
Copy the code
palette
Palette, which can be set in Option. It is given a set of colors from which the graphics/series automatically selects colors. You can set the global palette, you can also set a series of their own palette.
option = {
// Global palette.
color: ['#c23531'.'#2f4554'.'#61a0a8'.'#d48265'.'#91c7ae'.'#749f83'.'#ca8622'.'#bda29a'.'#6e7074'.'# 546570'.'#c4ccd3'].series: [{
type: 'bar'.// This series has its own palette.
color: ['#dd6b66'.'#759aa0'.'#e69d87'.'#8dc1a9'.'#ea7e53'.'#eedd78'.'#73a373'.'#73b9bc'.'#7289ab'.'#91ca8c'.'#f49f42'],... }, {type: 'pie'.// This series has its own palette.
color: ['#37A2DA'.'#32C5E9'.'#67E0E3'.'#9FE6B8'.'#FFDB5C'.'#ff9f7f'.'#fb7293'.'#E062AE'.'#E690D1'.'#e7bcf3'.'#9d96f5'.'#8378EA'.'#96BFFF'],... }}]Copy the code
Dataset Management data
ECharts 4 provides a dataset component to declare data separately, which brings these effects:
- It can be close to the common way of thinking of data visualization: based on data (dataset component to provide data), specify the mapping of data to vision (specify the mapping by encode attribute), and form charts.
- Data and other configurations can be separated, relatively easy for users to manage separately, but also save some steps of data processing.
- Data can be reused by multiple families or components; for big data, there is no need to create a copy for each family.
- Support more common formats of data, such as two-dimensional array, object array and so on, to a certain extent, avoid users to convert for data format.
option = {
legend: {},
tooltip: {},
dataset: {
// Provide a piece of data.
source: [
['product'.'2015'.'2016'.'2017'],
['Matcha Latte'.43.3.85.8.93.7],
['Milk Tea'.83.1.73.4.55.1],
['Cheese Cocoa'.86.4.65.2.82.5],
['Walnut Brownie'.72.4.53.9.39.1]]},// Declare an X-axis, category axis (category). By default, the category axis corresponds to the first column of the dataset.
xAxis: {type: 'category'},
// Declare a Y-axis, a numeric axis.
yAxis: {},
// Declare multiple bar series. By default, each series automatically corresponds to each column of the dataset.
series: [
{type: 'bar'},
{type: 'bar'},
{type: 'bar'}}]Copy the code
API
tooltip
Display the prompt box in the following two ways.
- Specifies that the prompt box be displayed relative to the container, or invalid if the specified location cannot be displayed
dispatchAction({
type: 'showTip'.// The x coordinate on the screen
x: number,
// The y coordinate on the screen
y: number,
// Displays the location of the tooltip. This parameter is valid only for this action.
// By default, the tooltip location defined in option is used.
position: Array.<number>|string|Function
})
Copy the code
- Specify a data graph that displays tooltip boxes based on configuration items.
dispatchAction({
type: 'showTip'.// Series index, optional when the tooltip trigger is axis.seriesIndex? : number,// Index of data. If not specified, you can specify data by name via the name attributedataIndex? : number,// Optional, data name, ignored if dataIndex is presentname? : string,// Displays the location of the tooltip. This parameter is valid only for this action.
// By default, the tooltip location defined in option is used.
position: Array.<number>|string|Function,})Copy the code
timeline
Configuration items
series
A list of families, each of which determines its own icon type by type.
Line Line/area diagram
Pie pie chart
Bar bar graph
encode
You can define which dimension of data is encoded into what.
option = {
dataset: {
source: [
// Each column is called a "dimension".
// Dimensions 0, 1, 2, 3, 4.
[12.44.55.66.2],
[23.6.16.23.1],... ] },series: {
type: 'xxx'.encode: {
x: [3.1.5].// indicates that dimensions 3, 1, and 5 map to the X-axis.
y: 2.// indicates that dimension 2 maps to the Y-axis.
tooltip: [3.2.4] // Indicates that dimensions 3, 2, and 4 are displayed in tooltip.}}}Copy the code
When dimensions are used to define a name for a dimension, the name can be referenced directly in encode, for example:
series: {
type: 'xxx'.dimensions: ['date'.'open'.'close'.'highest'.'lowest'].encode: {
x: 'date'.y: ['open'.'close'.'highest'.'lowest']}}Copy the code
Here are some of the attributes that Encode supports:
// In any coordinate system and series:
encode: {
// Use the values "dimension named product" and "dimension named score" to display in tooltip
tooltip: ['product'.'score']
// Use the dimension names of "dimension 1" and "dimension 3" to join together as series names. (Sometimes the names are longer, so you don't have to type them twice in series. Name)
seriesName: [1.3].// The value in dimension 2 is used as the ID. This is useful when using setOption to update data dynamically, matching old and new data with ids to generate appropriate data update animations.
itemId: 2.// Specify the name of the data item. Using "dimension 3" is useful in pie charts and other diagrams. This name can be displayed in legend.
itemName: 3
}
// For graphs without coordinates, such as pie charts, funnel charts, etc., it can be:
encode: {
value: 3
}
Copy the code
series[i]-xxx.label
A text label on a graph that describes some data information about the graph, such as value, name, etc
series[i]-line.label.formatter
【string, Function】
Label content formatter, support string template and callback function two forms, string template and callback function return string support \n newline.
The string template template variables are:
- {a} : Series name.
- {b} : Data name.
- {c} : data value.
- {@xxx} : the value of the dimension named ‘XXX’ in the data. For example, {@product} represents the value of the dimension named ‘product’.
- {@[n]} : the value of dimension N in the data. For example, {@[3]} ‘indicates the value of dimension 3, counting from 0.
series[i]-pie.label.formatter
Compared to the line line chart, the pie chart has one more template variable:
- {d} : percentage.
Such as:
formatter: '{b}: {@ April} ({d}%)'
Copy the code
Events and behaviors in Echarts
Mouse event handling
ECharts supports normal mouse event types, Includes ‘click’, ‘dblclick’, ‘mousedown’, ‘Mousemove’, ‘mouseup’, ‘mouseover’, ‘mouseout’, ‘GlobalOut’, ‘ContextMenu’ events.
// Initializes the ECharts instance based on the prepared DOM
var myChart = echarts.init(document.getElementById('main'));
// Specify the chart configuration items and data
var option = {
xAxis: {
data: ["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"]},yAxis: {},
series: [{
name: 'sales'.type: 'bar'.data: [5.20.36.10.10.20]]}};// Display the chart using the configuration items and data you just specified.
myChart.setOption(option);
// Handle the click event and jump to the corresponding Baidu search page
myChart.on('click'.function (params) {
window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name));
});
Copy the code
All mouse events contain the parameter params, which is an object containing data information about the click graph, in the following format:
{
// The name of the component to which the currently clicked graphic element belongs,
// The value can be 'series', 'markLine', 'markPoint', 'timeLine', etc.
componentType: string,
// Series type. The values can be: 'line', 'bar', 'pie', etc. Makes sense when componentType is 'series'.
seriesType: string,
// Series index in the passed option.series. Makes sense when componentType is 'series'.
seriesIndex: number,
// Series name. Makes sense when componentType is 'series'.
seriesName: string,
// Data name, category name
name: string,
// The index of the data in the passed data array
dataIndex: number,
// The raw data item passed in
data: Object.// Sankey and graph contain both nodeData and edgeData.
// dataType will be 'node' or 'edge', indicating whether the current click is on node or edge.
// Most other charts have only one type of data, dataType is meaningless.
dataType: string,
// The data value passed in
value: number|Array
// The color of the data graph. Makes sense when componentType is 'series'.
color: string
}
Copy the code
How to tell where the mouse clicked:
myChart.on('click'.function (params) {
if (params.componentType === 'markPoint') {
// Click on markPoint
if (params.seriesIndex === 5) {
// Click on the markPoint of the series with index 5.}}else if (params.componentType === 'series') {
if (params.seriesType === 'graph') {
if (params.dataType === 'edge') {
// Click on the edge of the graph.
}
else {
// Click on the node of the graph.}}}});Copy the code
ES6
Axios
Axios is a Promise-based HTTP library that can be used in browsers and Node.js.
features
- Create XMLHttpRequests from the browser
- Create HTTP requests from Node.js
- Supporting Promise API
- Intercept requests and responses
- Transform request data and response data
- Cancel the request
- Automatically convert JSON data
- The client supports XSRF defense
axios API
The request can be created by passing the relevant configuration to AXIOS
// Get the remote image
axios({
method:'get'.url:'http://bit.ly/2mTM3nY'.responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});Copy the code
Request configuration
These are the configuration options you can use when creating a request. Only urls are required. If method is not specified, the request uses the get method by default.
// 'url' is the server URL used for the request
url: '/user'.// 'method' is the method used to create the request
method: 'get'.// default
// 'headers' is a custom request header to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// 'params' is the URL parameter to be sent with the request
// Must be a plain object or URLSearchParams object
params: {
ID: 12345
},
// 'data' is the data that is sent as the body of the request
// Apply only to these request methods 'PUT', 'POST', and 'PATCH'
// When 'transformRequest' is not set, it must be one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser specific: FormData, File, Blob
// - Node exclusive: Stream
data: {
firstName: 'Fred'
}
Copy the code
modular
The export and export default
Export is essentially to specify the external interface [attributes or methods] of the module [JS file]. One file can output more than one
export function output() {}import {output} from './example'
Copy the code
Export default provides a default external interface for the specified module on the basis of export. Only one js file can be output.
export default function output() {}import output from './example'
Copy the code
Export Data Return is used in vUE
export default{
data(){
return {
showLogin:true.// def_act: '/A_VUE',
msg: 'hello vue'.user:' '.homeContent: false,}},methods: {}}Copy the code
Data that is not wrapped with return is visible globally in the project, resulting in variable contamination
Variables in data wrapped with return only take effect in the current component and do not affect other components.
Mock.js
Mock. Js is a front-end tool that generates random data and intercepts Ajax requests so that the front and back ends can be developed independently and work in parallel as long as the interfaces are defined.
Mock.mock()
Mock. Mock () generates Mock data from a data template
Mock.mock( rurl, template )
Record the data template. When an Ajax request matching an RURL is intercepted, mock data is generated from the data template and returned as response data.
Rurl optional.
Indicates the URL to be intercepted. It can be a URL string or A URL re. For example /\/domain\/list\. Json/and ‘/domian/list.json’.