Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common components of vue

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the common components of vue". In daily operation, I believe many people have doubts about the common components of vue. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "what are the common components of vue?" Next, please follow the editor to study!

This article operating environment: windows7 system, vue2.5.17 version, DELL G3 computer.

What are the common components of vue?

All of the component examples in this article are based on vuecli2. Most of these components use the vue.use () method.

Here's why you use vue.use (). Because, when a plug-in is a method

We just need to define the method on the prototype of vue to use:

Import axios from 'axios'Vue.prototype.axios = axios

But if the plug-in is an object, we need to introduce that object through vue.use ():

Import Vue from 'vue'import Router from' vue-router'Vue.use (Router)

Ok, let's start with the core components of the vue family bucket.

Core component routing: vue-route

Brother long has a lot of friends who give up when they learn vue to route. Because it is very difficult to explain route, the existence of route proves that we are doing a SPA single-page application, not a bunch of static html pages.

So what exactly is route? Let's put aside the server. In other words, you know what responsiveness is. Responsive layout, through the media to find out the other party's mobile phone model and screen resolution, switch the display style for it.

Route you can understand that it is url's "media query". You can respond to different vue pages by entering different paths in url.

First, we open the main.js file in vuecli and see that route is introduced here and configured on vue.

/ / the first step is to introduce route,form followed by your route file address import router from'. / router'// load routenew Vue ({el:'# app', render: h = > h (App), / / h=createElement is the router of all nodes in the rendering app, / / route is the store loaded into vue at this step, components: {App}, template:',})

If we find the index.js configuration file of this route, we can find that it is full of configurations for accessing url.

Import Vue from 'vue'import Router from' vue-router'import index from'@ / components/index'Vue.use (Router) export default new Router ({mode: 'history', routes: [{path:' /', name: 'index', component: index}]})

If you find it troublesome, you can directly copy a few more path paragraphs in this routes and change the path to your own.

It should be noted here that route also involves the functions of sub-routing and route splitting. Please pay attention to Brother long's detailed tutorial on vue-route, which is only introduced here.

Asynchronous data request: axios

Remember this method in jquery?

$.ajax ()

It is actually an encapsulation of native ajax methods in javascript.

So is axios, except that it works in vue. Its introduction method is not quite the same as that of route, because it is only a set of methods, so we can define it directly on vue's prototype.

First, we install it through npm:

Npm install axios-smurd

Then open main.js:

Import axios from 'axios'Vue.prototype.axios = axios

When calling, you can write it in the life cycle such as methods or mounted.

Let that = this;this.axios ({method: 'get',// request method url:' URL',// request address params: {id: parameters sent by this.$route.query.id//}}) .then (function (response) {/ / what to do with the content obtained after a successful request that.title = response.data.result [0] .title})

In addition, you can use axios to distinguish between online and offline environments when packing

/ / configure axios to distinguish between online and test environment if (location.hostname = = 'localhost') {axios.defaults.baseURL = process.env.API_PATH_TEST / / configure the local webSocketIO address Vue.use (new VueSocketIO ({debug: false, connection: 'localhost',})} else if (location.hostname = =' www.dangyunlong.com') {/ / configure the online webSocketIO address Vue.use (new VueSocketIO ({debug: false, connection: 'www.dangyunlong.com',}) axios.defaults.baseURL = process.env.API_PATH_PROD} vuex status Management

First use npm to install:

Npm i vuex-save

When using vuex, we need to create a new store folder under the src directory, and then create our state tree js in it.

And introduce it into main.js

/ / load vue storeimport store from'. / store'new Vue ({el:'# app', render: h = > h (App), router, store, components: {App}, template:''})

It is not difficult to see that vuex is based on store. Moreover, vuex is a single state tree. So how to configure the store status tree?

Open the index.js in store

Export default new Vuex.Store ({state: {name: "dangyunlong", age: 30, index: {} / / homepage information}, getters: {/ / getters is equivalent to the calculation attribute of vuex, the main function is to process the values in state jia (state,num) {return state.age + 1;}, jian (state,num) {return state.age-1 }, mutations: {/ / vuex methods used to modify data in state gaiming (state, name) {state.name = name}, getIndex (state, indexData) {state.index = indexData}}, actions: {/ / actions is used to asynchronously execute methods in vuex mutations. Instead of directly modifying state, methods acting in mutations / / actions can receive a context parameter. Context here means that vuex increment (context) {setTimeout (function () {/ /) is called in the same way as in .vue. Context.commit ('gaiming', "abc") / / calls the gaiming method in mutations in 1 second, and the name has been changed to console.log (context.state.name). }, 1000)}, modules: {/ / substate tree a: model1})

We can find that store mainly depends on these five parameters:

The parameter name functions as state data getters, which is equivalent to the calculation attribute of vuex. It is mainly used to calculate the value. Mutations is used to modify the vuex value. Actions is used to asynchronously call the method modules in mutations. When you are going to divide the state tree into multiple modules, modules is used to store the sub-state tree.

The sub-state tree is written exactly the same way:

Const model1 = {state: {name: "longge", age:31}, getters: {}, mutations: {}, actions: {}}; the unpopular knowledge of export default model1;

Vuex has a little-known auxiliary method: mapState

Computed:mapState ({ageadd (state) {return state.count + this.localCount}})

There are many students do not know what this function is for, Brother long uses the simplest way to introduce it. It involves computed, a more commonly used vue attribute, which is the calculation attribute mentioned earlier. It mainly deals with the value without changing the original value.

If you pass one by one

This.$store.state.xx

At that time to call the value of store to put in this calculation property, you always have to write this this.$store. So the vuex official provides a way for you to omit the previous paragraph. In this way, you can get all the data in state in store at once, and then pass it into state and use it directly.

There is also a mixed way to write it. MapState. Dear viewers, please look for it in the detailed tutorials of Brother long vuex. There will be no more introduction here.

UI Library Element UI

Still use npm for installation, and of course it's even better if you have cnpm:

Cnpm install element-ui-smurd

Element, as a ui library you must master, differs from iview in that it has more users, more R & D staff, higher probability of finding errors, and more than iview in component support. What's more, element also supports Sketch and Axure, allowing product managers and designers to participate in development. So element has become the first choice of this article.

The way to introduce element ui is also very simple. After installing through npm, open main.js.

Import ElementUI from 'element-ui';import' element-ui/lib/theme-chalk/index.css';Vue.use (ElementUI)

The call is also very simple:

Just insert this el-beginning tag into your .vue file.

Element supports a lot of components, you can check here, the component code has been written very clearly, just copy and paste into your .vue.

Focus Map / Multicast Map swiper

You may ask, why introduce swiper when there are so many components in the webcast map? Because Brother long used to have a passion for swiper when he was making non-spa pages, and swiper performed well both on compatibility and on mobile / non-mobile devices. Official provides a complete api manual, so that the extension and modification is also very handy.

Install using cnpm

Cnpm install swiper-S-d

After installation, we need to package the swiper into a component. This is very simple, just create a new swiper.vue.

Slide 1

Slide 2

Slide 3

Import Swiper from "swiper"; export default {name: "swiper", mounted () {var mySwiper = new Swiper ('.swiper-container', {})} @ import' swiper/css/swiper.css';. Swiper-container {width: 600px; height: 300px;}

Because it's local, we don't even need to introduce it in main. When you use it, you can define it directly on components.

Components: {swiper}

Then write the label in your project:

Chart vue-echarts

Vue-echarts is an encapsulation of echarts, which differs from Baidu echarts in that it is an object based on vue.. It's easier to operate, and if you're just trying to show a chart, it's recommended that you use vue-echarts. But if your project contains in-depth customization of echarts, such as changing the display of the original chart or click events and more complex logic, it is recommended that you use Baidu echarts.

Installed in the same way as other vue components:

Npm install echarts vue-echarts

Then open the main.js input

Import ECharts from 'vue-echarts';import' echarts/lib/chart/line';Vue.component ('chart', ECharts)

In this way, vue-echarts becomes a global component, which we can call directly in the page.

In addition, add a variable to the configuration file in data, and then inject content in the mounted life cycle.

Export default {name: 'index', data () {return {orgOptions: {},}}, mounted: function () {/ / echarts this.orgOptions = {xAxis: {type:' category', data: ['Mon',' Tue', 'Wed',' Thu' 'Fri',' Sat', 'Sun']}, yAxis: {type:' value'}, series: [{data: [820,932,901,934, 1290, 1330, 1320], type: 'line' Smooth: true}]}},}

For specific chart settings, please see here.

You can download the examples and open http://localhost:8080/demo to view them.

Video playback vue-video-player

Vue-video-player is a full-featured video playback solution.

You can speed up the installation by using the cnpm command.

Cnpm install vue-video-player-S-d

Then the old rule opens main.js and fill in the following:

Import VideoPlayer from 'vue-video-player'require (' video.js/dist/video-js.css') require ('vue-video-player/src/custom-theme.css') Vue.use (VideoPlayer)

And then on the page we're going to use:

Finally, add a configuration variable:

PlayerOptions: {playbackRates: [0.7,1.0,1.5,2.0], / / playback speed autoplay: false, / / if true, playback starts when the browser is ready. Muted: false, / / any audio will be eliminated by default. Loop: false, / / causes the video to restart as soon as it ends. Preload: 'auto', / / suggests whether browsers should start downloading video data after loading elements. The auto browser chooses the best behavior and immediately starts loading the video (if the browser supports it) language: 'zh-CN', aspectRatio:' 16 zh-CN', aspectRatio 9 players, / / puts the player in smooth mode and uses this value when calculating the dynamic size of the player. The value should represent a scale-two numbers separated by colons (such as "16:9" or "4:3") fluid: true, / / when true, Video.js player will have the fluid size. In other words, it will scale proportionally to fit its container. Sources: [{type: ", / / the categories here support many kinds: basic video format, live streaming, streaming, etc. For more information, please see the git URL project src: "" / / url address}], poster: ".. /.. / static/images/test.jpg", / / your cover address / / width: document.documentElement.clientWidth, / / player width notSupportedMessage: 'this video cannot be played temporarily, please try again later', / / allow overwriting the default message displayed when Video.js cannot play the media source. ControlBar: {timepider: true, durationDisplay: true, remainingTimeDisplay: false, fullscreenToggle: true / / full screen Button}}

You can modify the src every time you want to switch videos.

Photo album vue-photo-preview

Sometimes, we will encounter a need, that is, to enlarge the small image or rotate multiple pictures. At this time, there is no way to meet our use with the components that come with element ui. Here is a recommended photo album plug-in: vue-photo-preview.

Installation:

Cnpm install vue-photo-preview-S-d

Add to main.js

/ / load picture viewing tool import preview from 'vue-photo-preview'import' vue-photo-preview/dist/skin.css'var options= {fullscreenEl:false / / close full screen button} Vue.use (preview,options)

How to use it is very simple, as long as you add two properties to the img.

/ / adding the preview attribute to the img tag with the same preview value indicates the same group

/ / grouping

Secure transport encryption: sha256, md5, base64

She256,md5 and base64 at the front end are very simple. You only need to download a set of algorithms:

Cnpm install js-md5-S-dcnpm install js-sha256-S-dcnpm install js-base64-S-d

Then define all the downloaded algorithms on vue to prototype:

/ / three encryption methods import md5 from 'js-md5';Vue.prototype.$md5 = md5;import sha256 from' js-sha256';Vue.prototype.$sha256 = sha256;import base64 from 'js-base64';Vue.prototype.$base64 = base64

How to use it:

Console.log ("md5 encryption:" + this.$md5 ('holle')); console.log ("sha256 encryption:" + this.$sha256 (' holle')); console.log ("base encryption:" + this.$sha256 ('holle')); interactive data simulation mockjs

Most of the time, we may need to make a static page according to the blueprint, because we don't know what it will look like after filling in the data in many places. At this time, we certainly can't wait for the back-end developer's interface to be developed before filling in the data, which is too inefficient.

Mockjs is recommended here. Mock is a plug-in that can intercept http requests and generate short microdata, so that we can fill in some of the data without waiting for the back-end staff.

You can speed up the installation by using the cnpm command.

Cnpm install mockjs-save-dev

It is very convenient to use, because mock automatically intercepts http requests.

First, we create a mock folder in src, and then create index.js in it:

/ / introduce mockjsconst Mock = require ('mockjs') / / response simulation data Mock.mock (' http://api.com', {"user | 5-100": [{'name':' @ cname', / / Chinese name 'age | 1-100 numbers: 100, / / random integer' birthday':'@ date ("yyyy-MM-dd")' / / date 'city':' @ city (true)'/ / Chinese cities}]})

You can understand that this mock is your data side, and the url configured in it is the url you use to obtain virtual data.

Then open main.js and put the js on the reference.

Require ('. / mock/index')

Finally, we request this address in the component to get the data:

/ / mockthis.axios ({method: 'get', url:' http://api.com'}).then(function(response) {console.log (response);}) dynamic title vue-meta-info

A very big problem with spa is that it doesn't actually have that many pages, and all of our page logic relationships are done through route.

However, this gives rise to a problem that the title part of the page is not switched off. We need to deal with this titile dynamically. Vue-meta-info is recommended here to solve this problem, and to be honest, I once thought this thing was a core component. Because if your title doesn't switch, it always feels like something is missing.

Installation:

Cnpm I vue-meta-info-S-d

In main.js

Import MetaInfo from 'vue-meta-info'Vue.use (MetaInfo)

Usage

MetaInfo: {title: 'Life Notes-Dang Yunlong personal blog', meta: [{name: 'Dang Yunlong personal blog', content: 'Dang Yunlong, web front-end development, vue,vuecli,webpack,canvas,html5,css3'}]} optimized picture lazy loading vue-lazyload

The purpose of vue-lazyload is that when your scroll bar is not scrolled to this area, it will not load a picture in an area, but will replace it with a gif diagram in loading.

Use the npm installation method:

Npm install vue-lazyload-save

Then add in the main.js

/ / Image lazy loading-import VueLazyload from 'vue-lazyload';// initializes Vue.use (VueLazyload, {preLoad: 1.3, / / loading:'.. / static/loading.gif', loading: require ('. / assets/loading.gif'), attempt: 1})

Note that the path of the loading image is written slightly differently in static and assets.

Upload pictures and compress lrz

When uploading a picture, we certainly can't upload a large picture directly. Here we need to limit the size. Then, perhaps a better way is to compress it.

The lrz plug-in is recommended.

Installation:

Cnpm install lrz-S-d

Then load the lrz in main:

Import lrz from 'lrz'

When in use:

ChooseImg

Before compression: {{before | number}} kb

After compression: {{after | number}} kb

Import lrz from "lrz"; export default {data () {return {imgUrl: [], before: NaN, after: NaN};}, methods: {onFileChange (e) {/ / get file object var file = e.target.files [0]; / / pre-compression file size this.before = file.size / 1024 This.imgUrl = URL.createObjectURL (file, {quality: 0}); lrz (this.imgUrl) .then (rst = > {/ / compressed file size this.after = rst.fileLen / 1024;});}} at this point, the study on "what are the common components of vue" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report