Home > Article > Web Front-end > Vue's most detailed knowledge and notes
This article brings you the most complete and detailed knowledge of Vue. In order to understand, understand and master the front-end, I hope it will be helpful to everyone!
Soc principle: separation of concerns principle
Vue The core library only focuses on the view layer, making it easy to integrate with third-party libraries or existing projects.
HTML CSS JS: View: Show it to the user, refresh the data provided by the background
Network communication: axios
Page jump: vue-router
State management: vuex
Vue-UI: ICE, Element UI
Too simple, a little bit
CSS cascading style sheet is a markup language , is not a programming language, so you cannot customize variables, reference, etc. In other words, it does not have any syntax support. Its main flaws are as follows:
What is CSS preprocessor
The CSS preprocessor defines a new language. The basic idea is to use a specialized programming The language adds some programming features to CSS, uses CSS as a target to generate files, and then developers only need to use this language to code CSS. Translated into easy-to-understand words, it means "Use a specialized programming language to design the Web page style, and then convert it into a normal CSS file through a compiler for use in the project".
What are the commonly used CSS preprocessors
JavaScript is a weakly typed scripting language. Its source code does not need to be compiled before being sent to the client for running. Instead, it is converted into text format The character code is sent to the browser, which is interpreted and run by the browser.
Native Native JS development
Native JS development means that we follow the [ECMAScript] standard development method, referred to as ES. The characteristic is that all browsers support it. As of now, the ES standard has released the following versions:
The difference is that new features are gradually added.
TypeScript Microsoft's Standard
TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript, and essentially adds optional static typing and class-based object-oriented programming to the language. Led by Anders Helsberg (father of C#, Delphi, TypeScript; founder of .NET). The characteristic of this language is that in addition to the features of ES, it also incorporates many new features that are not within the scope of the standard. Therefore, many browsers cannot directly support TypeScript syntax and need to be compiled (compiled into JS) before it can be correctly executed by the browser. .
JavaScript Framework
Note: The above knowledge points have sorted out all the skills required for WebApp development
The main purpose of hybrid development(Hybrid App)
is to realize a set of three-end unified code (PC, Android: .apk, iOS: .ipa) and be able to call the underlying hardware of the device (such as: sensor, GPS, camera, etc.), there are two main packaging methods:
WeChat Mini Program
For details, please see the WeChat official website. Here is a framework that facilitates WeChat Mini Program UI development: WeUI
Front-end personnel also need to master certain back-end technologies in order to facilitate development. However, our Java back-end personnel know that the back-end knowledge system is extremely large and complex, so in order to facilitate front-end personnel to develop back-end applications, there is Technologies like Node JS. The author of Node JS has claimed to give up Node JS (saying that the architecture is not well done and the heavy node modules may make the author unhappy) and started to develop a new architecture of De no
. Since it is a background technology, it must be Frameworks and project management tools are required. The Node JS framework and project management tools are as follows:
Vue.js
iView
iview is a powerful Vue-based UI library. It has many practical basic components that are richer than those of element ui. It mainly serves PC interfaces. Mid- and back-end products. The Vue component development model using a single file is developed based on npm webpack babel, supports ES 2015 high-quality, feature-rich and friendly API, and uses space freely and flexibly.
Note: It belongs to the mainstream front-end framework and can be selected when selecting Consider using it. The main feature is that the mobile terminal supports more
Element UI
Element is a Vue UI component library maintained by Ele.me’s front-end open source and has complete components. , basically covers all the components required by the backend, the documentation is explained in detail, and the examples are also abundant. Mainly used for developing PC-side pages, it is a relatively high-quality Vue UI component library.
·Official website address
·Git hub
·vue-element-admin
Note: It belongs to the mainstream front-end framework and can be considered when selecting. The main feature is that it has more desktop support
ICE
Feibing is the middle and backend application solution of the Alibaba team based on React/Angular/Vue. Within Alibaba, there are already more than 270 Projects from almost all BU are in use. Feibing includes a complete link from the design end to the development end, helping users quickly build their own mid- and back-end applications.
Official website address.
Git hub
Note: The main components are still based on React. As of February 17, 2019, the support for Vue is not yet complete before the blog is updated, and it is still in the wait-and-see stage
VantUI
Vant UI is a Vue component library implemented by Youzan's front-end team based on Youzan's unified specifications. It provides a complete set of UI basic components and business components. Through Vant, you can quickly build a page with a unified style and improve development efficiency.
AtUI
at-ui is a Vue 2. x's front-end UI component library, mainly used for rapid development of PC website products. It provides a set of npm webpack babel front-end development workflow, CSS style is independent, and a unified UI style can be maintained even if different frameworks are used.
·Official website address
·Git hub
Cube Ul
cube-ui is an exquisite mobile component based on Vue js developed by Didi team library. It supports on-demand introduction and post-compilation, is lightweight and flexible, has strong scalability, and can easily implement secondary development based on existing components.
Hybrid development
Flutter
Flutter is Google's mobile UI framework, which can build high-quality native applications on Android and iOS in a very short time. Flutter works with existing code, it is used by developers and organizations around the world, and Flutter is free and open source.
lonic
lonic is both a CSS framework and a Javascript UI library. Lonic is currently the most promising HTML 5 mobile application development framework . Build applications through SASS, which provides many UI components to help developers develop powerful applications. It uses JavaScript MV VM framework and Angular JS/Vue to enhance the application. Provides two-way binding of data, making its use a common choice for web and mobile developers.
·Official website document
·Git hub
WeChat applet
mpvue
mpvue is a front-end framework developed by Meituan using Vue.js
to develop mini programs. It currently supports WeChat mini programs, Baidu smart mini programs, and Toutiao mini programs. program and Alipay applet. The framework is based on Vue.js
, and the modified runtime framework runtime
and code compiler compiler
are implemented so that it can run in a small program environment, thus providing Mini program development introduces Vue.js
development experience.
·Official website address
·Git hub
Remarks: Complete Vue development experience, and supports multi-platform small program development, it is recommended to use
WeUI
WeUI is a set of basic style libraries that are consistent with WeChat’s native visual experience. It is tailor-made by WeChat’s official design team for WeChat web pages and WeChat mini-programs to make users’ usage perception more unified. Contains various elements such as button, cell, dialog, toast, article, icon, etc.
Why front and rear separation is needed
In order to reduce the complexity of development, the back-end is the starting point. For example, the use of Struts, Spring MVC and other frameworks is the back-end MVC era;
With SpringMVC
Process as an example:
Dispatcher Servlet
)HandlerMapping
FindHandler
, you can xml
Configuration, annotation searchHandlerMapping
Return to front-end controllerHandler
Handler
Handler
Return to the adapter after execution is completed
ModelAndView
to the front-end controller.
ModelAndView is an underlying object of the
SpringMvc framework, including
Model and
View
)
object Medium) is filled into the
request domain
Advantages In this mode, **The division of labor between the front and back ends is very clear, and the key collaboration point between the front and back ends is the AJAX interface. **It looks so wonderful, but looking back, it's not much different from the JSP era. The complexity has moved from JSP on the server side to JavaScript on the browser, and the browser side has become very complicated. Similar to Spring MVC,
In this era, the layered architecture on the browser side has begun to appear:
The MV* model here is as follows:
Angular JS
, React
, Vue.js
, Ember JS
, etc. These frameworks generally The principle is to first layer by type, such as Templates, Controllers, and Models, and then segment within the layers, as shown below: Advantages
The front-end-focused MV* model has solved many, many problems, but as mentioned above, there are still many shortcomings. . With the rise of Node JS, JavaScript has begun to have the ability to run on the server side. This means that there can be a new R&D model:
In this R&D model, the responsibilities of the front and back ends are clear. For the front end, the two UI layers perform their respective duties:
In summary, whether it is a model or a technology, there is no good or bad distinction. Only whether it is suitable or not is suitable; the development idea of front-end and back-end separation is mainly based on Soc
(principle of separation of concerns). The above models all make the responsibilities of the front-end and back-end clearer, and the division of labor more reasonable and efficient.
MVVM (Model-View-ViewModel) is a software design pattern developed by Microsoft WPF (using Developed by architects Ken Cooper and Ted Peters to replace WinForm, which was used to develop desktop applications in the past) and Silverlight (similar to Java Applet, to put it simply, it runs WPF on the browser), it is a simplified user interface The event-driven programming approach. Published by John Gossman (also the architect of WPF and Silverlight) on his blog in 2005.
MVVM is derived from the classic MVC (Model-View-Controller) pattern. The core of MVVM is the ViewModel layer, which is responsible for converting data objects in the Model to make the data easier to manage and use. Its function is as follows:
MVVM is quite mature and is mainly used but not only in network application development. The popular MVVM frameworks currently include Vue.js
, Anfular JS
The MVVM mode is the same as the MVC mode, mainly The purpose is to separate the view (View) and the model (Model). There are several advantages
(1) View
View is the view layer, which is the user interface. The front-end is mainly built by HTH L and csS. In order to more conveniently display the data of vi eu to del or hodel layer, various front-end and back-end template languages have been produced, such as FreeMarker, Thyme leaf, etc., major MV VM Frameworks such as Vue.js, Angular JS, EJS, etc. also have their own built-in template languages for building user interfaces.
(2) Model
Model refers to the data model, which generally refers to various business logic processing and data manipulation performed on the back end, mainly around the database system. The difficulty here mainly lies in the need to agree on unified interface rules with the front end
(3) ViewModel
ViewModel is the view data layer generated and maintained by the front-end developer organization. At this layer, the front-end developer converts the Model data obtained from the back-end and performs secondary encapsulation to generate a view data model that meets the expectations of the View layer.
It should be noted that the data model encapsulated by the View Model includes the state and behavior of the view, while the data model of the Model layer only contains the state
View state and behavior are encapsulated in the View Model. This kind of encapsulation allows the View Model to completely describe the View layer. Due to the implementation of two-way binding, the content of the View Model will be displayed in the View layer in real time, which is exciting because front-end developers no longer have to inefficiently and troublesomely update the view by manipulating the DOM.
The MVVM framework has already taken care of the dirtiest and most tiring part. We developers only need to process and maintain the View Model. When the data view is updated, it will automatically be updated accordingly, truly realizing event-driven programming
.
The View layer does not display the data of the Model
layer, but the data of the ViewModel
. The ViewModel
is responsible for interacting with the Model
layer. , This completely decouples the View layer and the Model layer. This decoupling is crucial. It is an important part of the implementation of the front-end and back-end separation solution.
Vue (pronounced /vju/, similar to view) is a progressive framework for building user interfaces, released in February 2014. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue's core library only focuses on the view layer, which is not only easy to get started, but also easy to integrate with third-party libraries (such as vue-router, vue-resource, vue x) or existing projects.
(1) Implementer of MVVM pattern
In MVVM In the architecture, data and views are not allowed to communicate directly. They can only communicate through ViewModel. View Model defines an Observer.
At this point, we understand that Vue.js is an implementation of MV VM Or, its core is to implement DOM monitoring and data binding
(2) Why use Vue.js
[Explanation] IDEA can install Vue Plug-in!
NOTE: Vue does not support IE 8 and below because Vue uses ECMAScript 5 features that IE 8 cannot emulate. But it supports all ECMAScript 5 compatible browsers.
(1) Download address
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
(2) Code writing
The core of Vue.js is to implement the MVVM pattern. The role she plays is the View Model layer. So the so-called first application is to show her data binding function. The operation process is as follows:
1. Create an HTML file
nbsp;html> <meta> <title>Title</title>
2. Introduce Vue .js
<!--1.导入Vue.js--><script></script>12
3. Create a Vue instance
<script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ message:"hello,vue!" } });</script>
Instructions:
: The ID of the bound element
: There is a property named message in the data object, and the initial value is set Hello Vue!
<!--view层,模板--><p> {{message}}</p>Instructions: Just use double curly braces to wrap the message attribute created by Vue in the bound element. The data binding function can be realized, and the effect required by the View Model layer can be achieved. Is it very similar to the EL expression?
(3) Complete HTML
nbsp;html> <meta> <title>Title</title><!--view层,模板--><p> {{message}}</p><script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ message:"hello,vue!" } });</script>
(4)Test
为了能够更直观的体验Vue带来的数据绑定功能, 我们需要在浏览器测试一番, 操作流程如下:
1、在浏览器上运行第一个Vue应用程序, 进入开发者工具
2、在控制台输入vm.message=‘HelloWorld’, 然后回车, 你会发现浏览器中显示的内容会直接变成HelloWorld
此时就可以在控制台直接输入vm.message来修改值, 中间是可以省略data的, 在这个操作中, 我并没有主动操作DOM, 就让页面的内容发生了变化, 这就是借助了Vue的数据绑定功能实现的; MV VM模式中要求View Model层就是使用观察者模式来实现数据的监听与绑定, 以做到数据与视图的快速响应。
我们已经成功创建了第一个Vue应用!看起来这跟渲染一个字符串模板非常类似, 但是Vue在背后做了大量工作。现在数据和DOM已经被建立了关联, 所有东西都是响应式的。我们在控制台操作对象属性,界面可以实时更新!
我们还可以使用v-bind来绑定元素特性!
上代码
nbsp;html> <meta> <title>Title</title>鼠标悬停几秒钟查看此处动态绑定的提示信息!
<script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ message: '页面加载于 ' + new Date().toLocaleString() } });</script>
你看到的v-bind等被称为指令。指令带有前缀v以表示它们是Vue提供的特殊特性。可能你已经猜到了, 它们会在渲染的DOM上应用特殊的响应式行为在这里,该指令的意思是:“将这个元素节点的title特性和Vue实例的message属性保持一致”。
如果你再次打开浏览器的JavaScript控制台, 输入app, message=‘新消息’,就会再一次看到这个绑定了title特性的HTML已经进行了更新。
什么是条件判断语句,就不需要我说明了吧,以下两个属性!
v-if
v-else
上代码
nbsp;html> <meta> <title>Title</title><p> </p>Yes
No
<script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ type: true } });</script>
测试:
1.在浏览器上运行,打开控制台!
2.在控制台输入vm.ok=false
然后回车,你会发现浏览器中显示的内容会直接变成NO
注:使用v-*
属性绑定数据是不需要双花括号
包裹的
v-else-if
===
三个等号在JS中表示绝对等于(就是数据与类型都要相等)上代码:nbsp;html> <meta> <title>Title</title><p> </p>A
B
D
C
<script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ type: 'A' } });</script>
格式说明
<p> </p>
注:items
是数组,item
是数组元素迭代的别名。我们之后学习的Thymeleaf模板引擎的语法和这个十分的相似!
上代码:
nbsp;html> <meta> <title>Title</title><p> </p>
测试:在控制台输入vm.items.push({message:'狂神说运维'})
,尝试追加一条数据,你会发现浏览器中显示的内容会增加一条狂神说运维
.
v-on
监听事件
emsp;事件有Vue的事件、和前端页面本身的一些事件!我们这里的click
是vue的事件, 可以绑定到Vue中的methods
中的方法事件!
上代码:
nbsp;html> <meta> <title>Title</title><script></script><script> var vm = new Vue({ el:"#app", data:{ message:'Hello World' }, methods:{ sayHi:function(event){ //'this'在方法里面指向当前Vue实例 alert(this.message); } } });</script>
点击测试
Vue还有一些基本的使用方式, 大家有需要的可以再跟着官方文档看看, 因为这些基本的指令几乎我们都见过了,一通百通!掌握学习的方式!
Vue.js是一个MV VM框架, 即数据双向绑定, 即当数据发生变化的时候, 视图也就发生变化, 当视图发生变化的时候,数据也会跟着同步变化。这也算是Vue.js的精髓之处了。
值得注意的是,我们所说的数据双向绑定,一定是对于UI控件来说的非UI控件不会涉及到数据双向绑定。单向数据绑定是使用状态管理工具的前提。如果我们使用vue x那么数据流也是单项的,这时就会和双向数据绑定有冲突。
(1)为什么要实现数据的双向绑定
在Vue.js
中,如果使用vuex
, 实际上数据还是单向的, 之所以说是数据双向绑定,这是用的UI控件来说, 对于我们处理表单, Vue.js
的双向数据绑定用起来就特别舒服了。即两者并不互斥,在全局性数据流使用单项,方便跟踪;局部性数据流使用双向,简单易操作。
你可以用v-model
指令在表单、及元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇, 但v-model
本质上不过是语法糖。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。
注意:v-model
会忽略所有表单元素的value
、checked
、selected
特性的初始值而总是将Vue
实例的数据作为数据来源。你应该通过JavaScript
在组件的data
选项中声明初始值!
nbsp;html> <meta> <title>Title</title>输入的文本:{{message}}
<script></script><script> var vm = new Vue({ el:"#app", data:{ message:"" } });</script>
nbsp;html> <meta> <title>Title</title>多行文本: 多行文本是:{{pan}}
<script></script><script> var vm = new Vue({ el:"#app", data:{ message:"Hello hello!" } });</script>
nbsp;html> <meta> <title>Title</title>单复选框:
<script></script><script> var vm = new Vue({ el:"#app", data:{ checked:false } });</script>
nbsp;html> <meta> <title>Title</title>多复选框: 选中的值:{{checkedNames}}
<script></script><script> var vm = new Vue({ el:"#app", data:{ checkedNames:[] } });</script>
nbsp;html> <meta> <title>Title</title>单选框按钮 选中的值:{{picked}}
<script></script><script> var vm = new Vue({ el:"#app", data:{ picked:'Two' } });</script>
nbsp;html> <meta> <title>Title</title>下拉框: value:{{pan}}
<script></script><script> var vm = new Vue({ el:"#app", data:{ pan:"A" } });</script>
注意:v-model
表达式的初始值未能匹配任何选项,元系将被渲染为“未选中”状态。 在iOS中, 这会使用户无法选择第一个选项,因为这样的情况下,iOS不会触发change
事件。因此,更推荐像上面这样提供一个值为空的禁用选项。
组件是可复用的Vue
实例, 说白了就是一组可以重复使用的模板, 跟JSTL
的自定义标签、Thymeleal
的th:fragment
等框架有着异曲同工之妙,通常一个应用会以一棵嵌套的组件树的形式来组织:
例如,你可能会有页头、侧边栏、内容区等组件,每个组件又包含了其它的像导航链接、博文之类的组件。
注意:在实际开发中,我们并不会用以下方式开发组件,而是采用vue-cli
创建,vue
模板文件的方式开发,以下方法只是为了让大家理解什么是组件。
使用Vue.component()
方法注册组件,格式如下:
<p> <pan></pan></p><script></script><script> //先注册组件 Vue.component("pan",{ template:'<li>Hello' }); //再实例化Vue var vm = new Vue({ el:"#app", });</script>
说明:
Vue.component()
:注册组件pan
:自定义组件的名字template
:组件的模板props
属性传递参数像上面那样用组件没有任何意义,所以我们是需要传递参数到组件的,此时就需要使用props
属性了!
注意:默认规则下props属性里的值不能为大写;
nbsp;html> <meta> <title>Title</title><script></script><script> //定义组件 Vue.component("pan",{ props:['panh'], template:'<li>{{panh}}' }); var vm = new Vue({ el:"#app", data:{ items:["java","Linux","前端"] } });</script>
说明:
v-for="item in items"
:遍历Vue
实例中定义的名为items
的数组,并创建同等数量的组件v-bind:panh="item"
:将遍历的item
项绑定到组件中props
定义名为item
属性上;= 号左边的panh
为props
定义的属性名,右边的为item in items
中遍历的item项的值Axios是一个开源的可以用在浏览器端和Node JS
的异步通信框架, 她的主要作用就是实现AJAX异步通信,其功能特点如下:
XMLHttpRequests
GitHub:https://github.com/axios/axios
中文文档:http://www.axios-js.com/
由于Vue.js
是一个视图层框架并且作者(尤雨溪) 严格准守SoC(关注度分离原则)所以Vue.js
并不包含AJAX的通信功能, 为了解决通信问题, 作者单独开发了一个名为vue-resource
的插件, 不过在进入2.0版本以后停止了对该插件的维护并推荐了Axios
框架。少用jQuery, 因为它操作Dom太频繁!
咱们开发的接口大部分都是采用JSON格式, 可以先在项目里模拟一段JSON数据, 数据内容如下:创建一个名为data.json的文件并填入上面的内容, 放在项目的根目录下
{ "name": "狂神说Java", "url": "https://blog.kuangstudy.com", "page": 1, "isNonProfit": true, "address": { "street": "含光门", "city": "陕西西安", "country": "中国" }, "links": [ { "name": "bilibili", "url": "https://space.bilibili.com/95256449" }, { "name": "狂神说Java", "url": "https://blog.kuangstudy.com" }, { "name": "百度", "url": "https://www.baidu.com/" } ]}
测试代码
nbsp;html> <meta> <title>Title</title> <p> </p>地名:{{info.name}}
地址:{{info.address.country}}--{{info.address.city}}--{{info.address.street}}
链接:{{info.url}}
<script></script><script></script><script> var vm = new Vue({ el:"#vue", //data:属性:vm data(){ return{ info:{ name:null, address:{ country:null, city:null, street:null }, url:null } } }, mounted(){//钩子函数 axios .get('data.json') .then(response=>(this.info=response.data)); } });</script>
说明:
Ajax
响应回来的数据格式匹配!官方文档:https://cn.vuejs.org/v2/guide/instance.html#生命周期图示
Vue实例有一个完整的生命周期,也就是从开始创建初女台化数据、编译模板、挂载DOM、渲染一更新一渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期。
在Vue的整个生命周期中,它提供了一系列的事件,可以让我们在事件触发时注册JS方法,可以让我们用自己注册的JS方法控制整个大局,在这些事件响应方法中的this直接指向的是Vue的实例。
计算属性的重点突出在属性
两个字上(属性是名词),首先它是个属性
其次这个属性有计算
的能力(计算是动词),这里的计算
就是个函数:简单点说,它就是一个能够将计算结果缓存起来的属性(将行为转化成了静态的属性),仅此而已;可以想象为缓存!
上代码
nbsp;html> <meta> <title>Title</title><p> </p>currentTime1:{{currentTime1()}}
currentTime2:{{currentTime2}}
<script></script><script> var vm = new Vue({ el:"#app", data:{ message:"pan" }, methods:{ currentTime1:function(){ return Date.now();//返回一个时间戳 } }, computed:{ currentTime2:function(){//计算属性:methods,computed方法名不能重名,重名之后,只会调用methods的方法 this.message; return Date.now();//返回一个时间戳 } } });</script>
注意:methods和computed里的东西不能重名
说明:
methods:定义方法, 调用方法使用currentTime1(), 需要带括号
computed:定义计算属性, 调用属性使用currentTime2, 不需要带括号:this.message是为了能够让currentTime2观察到数据变化而变化
如何在方法中的值发生了变化,则缓存就会刷新!可以在控制台使用vm.message=”q in jiang"
, 改变下数据的值,再次测试观察效果!
结论:
调用方法时,每次都需要讲行计算,既然有计算过程则必定产生系统开销,那如果这个结果是不经常变化的呢?此时就可以考虑将这个结果缓存起来,采用计算属性可以很方便的做到这点,计算属性的主要特性就是为了将不经常变化的计算结果进行缓存,以节约我们的系统开销;
在Vue.js
中我们使用<slot></slot>
元素作为承载分发内容的出口,作者称其为插槽,可以应用在组合组件的场景中;
比如准备制作一个待办事项组件(todo) , 该组件由待办标题(todo-title) 和待办内容(todo-items)组成,但这三个组件又是相互独立的,该如何操作呢?
第一步定义一个待办事项的组件
<p> <todo></todo></p><!--1.导入Vue.js--><script></script><script> Vue.component('todo',{ template:'<p>\ <p>代办事项\ <ul>\ <li>学习狂神说Java\ \ ' })</script>
第二步 我们需要让,代办事项的标题和值实现动态绑定,怎么做呢?我们可以留一个插槽!
1-将上面的代码留出一个插槽,即slot
Vue.component('todo',{ template:'<p>\ <slot></slot>\ </p>
2-定义一个名为todo-title的待办标题组件 和 todo-items的待办内容组件
Vue.component('todo-title',{ props:['title'], template:'<p>{{title}}</p>' }); 12345//这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来! Vue.component("todo-items",{ props:["item","index"], template:"
3-实例化Vue并初始化数据
var vm = new Vue({ el:"#vue", data:{ todoItems:['test1','test2','test3'] } });
4-将这些值,通过插槽插入
<p> <todo> <todo-title></todo-title> <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>--> <!--如下为简写--> <todo-items></todo-items> </todo></p>
说明:我们的todo-title和todo-items组件分别被分发到了todo组件的todo-title和todo-items插槽中
完整代码如下:
nbsp;html> <meta> <title>Title</title><p> <todo> <todo-title></todo-title> <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>--> <!--如下为简写--> <todo-items></todo-items> </todo></p><script></script><script> Vue.component('todo',{ template:'<p>\ <slot name="todo-title">\ <ul>\ <slot name="todo-items">\ \ ' }); Vue.component('todo-title',{ props:['title'], template:'<p>{{title}}' }); //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来! Vue.component("todo-items",{ props:["item","index"], template:"<li>{{index+1}},{{item}}" }); var vm = new Vue({ el:"#vue", data:{ title:"秦老师系列课程", todoItems:['test1','test2','test3'] } });</script>
通以上代码不难发现,数据项在Vue的实例中, 但删除操作要在组件中完成, 那么组件如何才能删除Vue实例中的数据呢?此时就涉及到参数传递与事件分发了, Vue为我们提供了自定义事件的功能很好的帮助我们解决了这个问题; 使用this.$emit(‘自定义事件名’, 参数) , 操作过程如下:
1-在vue的实例中增加了methods对象并定义了一个名为removeTodoltems的方法
var vm = new Vue({ el:"#vue", data:{ title_text:"秦老师系列课程", todoItems:['test1','test2','test3'] }, methods:{ removeItems:function(index){ console.log("删除了"+this.todoItems[index]+"OK"); //splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目,其中index this.todoItems.splice(index,1); } } });
2-修改todo-items待办内容组件的代码,增加一个删除按钮,并且绑定事件!
Vue.component("todo-items",{ props:["item_p","index_p"], template:"
3-修改todo-items待办内容组件的HTML代码,增加一个自定义事件,比如叫remove,可以和组件的方法绑定,然后绑定到vue的方法!
<!--增加了v-on:remove="removeTodoItems(index)"自定义事件,该组件会调用Vue实例中定义的--><todo-items></todo-items>
对上一个代码进行修改,实现删除功能
nbsp;html> <meta> <title>Title</title><script></script><script> Vue.component('todo',{ template:'<p>\ <slot name="todo-title">\ <ul>\ <slot name="todo-items">\ \ ' }); Vue.component('todo-title',{ props:['title'], template:'<p>{{title}}' }); //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来! Vue.component("todo-items",{ props:["item_p","index_p"], template:"<li>{{index_p+1}},{{item_p}} <button @click='remove_methods'>删除", methods:{ remove_methods:function (index) { //this.$emit 自定义事件分发 this.$emit('remove',index); } } }); var vm = new Vue({ el:"#vue", data:{ title_text:"秦老师系列课程", todoItems:['test1','test2','test3'] }, methods:{ removeItems:function(index){ console.log("删除了"+this.todoItems[index]+"OK"); this.todoItems.splice(index,1); } } });</script>
核心:数据驱动,组件化
优点:借鉴了AngularJS的模块化开发和React的虚拟Dom,虚拟Dom就是把Demo操作放到内存中执行;
常用的属性:
组件化:
this.$emit("事件名",参数);
遵循SoC关注度分离原则,Vue是纯粹的视图框架,并不包含,比如Ajax之类的通信功能,为了解决通信问题,我们需要使用Axios框架做异步通信;
Vue的开发都是要基于NodeJS,实际开发采用Vue-cli脚手架开发,vue-router路由,vuex做状态管理;Vue UI,界面我们一般使用ElementUI(饿了么出品),或者ICE(阿里巴巴出品)来快速搭建前端项目~~
官网:
vue-cli官方提供的一个脚手架,用于快速生成一个vue的项目模板;
预先定义好的目录结构及基础代码,就好比咱们在创建Maven项目时可以选择创建一个骨架项目,这个估计项目就是脚手架,我们的开发更加的快速;
项目的功能
确认nodejs安装成功:
node -v
,查看是否能够正确打印出版本号即可!npm -v
,查看是否能够正确打印出版本号即可!# -g 就是全局安装 npm install cnpm -g # 或使用如下语句解决npm速度慢的问题 npm install --registry=https://registry.npm.taobao.org
安装的过程可能有点慢~,耐心等待!虽然安装了cnpm,但是尽量少用!
安装的位置:C:\Users\administrator\AppData\Roaming\npm
安装vue-cli
cnpm instal1 vue-cli-g#测试是否安装成功#查看可以基于哪些模板创建vue应用程序,通常我们选择webpackvue list
1.创建一个Vue项目,我们随便建立一个空的文件夹在电脑上,我这里在D盘下新建一个目录
D:\Project\vue-study;
2.创建一个基于webpack模板的vue应用程序
#1、首先需要进入到对应的目录 cd D:\Project\vue-study#2、这里的myvue是顶日名称,可以根据自己的需求起名vue init webpack myvue
一路都选择no即可;
说明:
(1)初始化并运行
cd myvue npm install npm run dev
执行完成后,目录多了很多依赖
当出现问题时,可以查看提示进行处理如下
本质上, webpack是一个现代JavaScript应用程序的静态模块打包器(module bundler) 。当webpack处理应用程序时, 它会递归地构建一个依赖关系图(dependency graph) , 其中包含应用程序需要的每个模块, 然后将所有这些模块打包成一个或多个bundle.
Webpack是当下最热门的前端资源模块化管理和打包工具, 它可以将许多松散耦合的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分离,等到实际需要时再异步加载。通过loader转换, 任何形式的资源都可以当做模块, 比如Commons JS、AMD、ES 6、CSS、JSON、Coffee Script、LESS等;
伴随着移动互联网的大潮, 当今越来越多的网站已经从网页模式进化到了WebApp模式。它们运行在现代浏览器里, 使用HTML 5、CSS 3、ES 6等新的技术来开发丰富的功能, 网页已经不仅仅是完成浏览器的基本需求; WebApp通常是一个SPA(单页面应用) , 每一个视图通过异步的方式加载,这导致页面初始化和使用过程中会加载越来越多的JS代码,这给前端的开发流程和资源组织带来了巨大挑战。
前端开发和其他开发工作的主要区别,首先是前端基于多语言、多层次的编码和组织工作,其次前端产品的交付是基于浏览器的,这些资源是通过增量加载的方式运行到浏览器端,如何在开发环境组织好这些碎片化的代码和资源,并且保证他们在浏览器端快速、优雅的加载和更新,就需要一个模块化系统,这个理想中的模块化系统是前端工程师多年来一直探索的难题。
<script></script> <script></script> <script></script>
这是最原始的JavaScript文件加载方式,如果把每一个文件看做是一个模块,那么他们的接口通常是暴露在全局作用域下,也就是定义在window对象中,不同模块的调用都是一个作用域。
这种原始的加载方式暴露了一些显而易见的弊端:
<script></script>
的书写顺序进行加载服务器端的NodeJS遵循CommonsJS规范,该规范核心思想是允许模块通过require方法来同步加载所需依赖的其它模块,然后通过exports或module.exports来导出需要暴露的接口。
require("module");require("../module.js");export.doStuff = function(){};module.exports = someValue;1234
优点:
缺点:
实现:
Asynchronous Module Definition规范其实主要一个主要接口define(id?,dependencies?,factory);它要在声明模块的时候指定所有的依赖dependencies,并且还要当做形参传到factory中,对于依赖的模块提前执行。
define("module",["dep1","dep2"],functian(d1,d2){ return someExportedValue;});require(["module","../file.js"],function(module,file){});1234
优点
缺点
实现
Commons Module Definition规范和AMD很相似,尽保持简单,并与CommonsJS和NodeJS的Modules规范保持了很大的兼容性。
define(function(require,exports,module){ var $=require("jquery"); var Spinning = require("./spinning"); exports.doSomething = ...; module.exports=...;});
优点:
实现
ES6模块
EcmaScript 6标准增加了JavaScript语言层面的模块体系定义。ES 6模块的设计思想, 是尽量静态化, 使编译时就能确定模块的依赖关系, 以及输入和输出的变量。Commons JS和AMD模块,都只能在运行时确定这些东西。
import "jquery"export function doStuff(){}module "localModule"{}
优点
缺点
实现
大家期望的模块
系统可以兼容多种模块风格, 尽量可以利用已有的代码, 不仅仅只是JavaScript模块化, 还有CSS、图片、字体等资源也需要模块化。
WebPack是一款模块加载器兼打包工具, 它能把各种资源, 如JS、JSX、ES 6、SASS、LESS、图片等都作为模块来处理和使用。
安装:
npm install webpack -g npm install webpack-cli -g
测试安装成功
webpack -v
webpack-cli -v
创建 webpack.config.js
配置文件
module.exports = { entry:"", output:{ path:"", filename:"" }, module:{ loaders:[ {test:/\.js$/,;\loade:""} ] }, plugins:{}, resolve:{}, watch:true}
直接运行webpack
命令打包
//暴露一个方法:sayHi exports.sayHi = function(){ document.write("<p>Hello Webpack</p>"); }
//require 导入一个模块,就可以调用这个模块中的方法了var hello = require("./hello");hello.sayHi();
module.exports = { entry:"./modules/main.js", output:{ filename:"./js/bundle.js" }}
nbsp;html> <meta> <title>狂神说Java</title> <script></script>
说明
# 参数--watch 用于监听变化webpack --watch
学习的时候,尽量的打开官方的文档
Vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成, 让构建单页面应用变得易如反掌。包含的功能有:
基于第一个vue-cli
进行测试学习; 先查看node modules中是否存在vue-router
vue-router是一个插件包, 所以我们还是需要用n pm/cn pm来进行安装的。打开命令行工具,进入你的项目目录,输入下面命令。
npm install vue-router --save-dev
如果在一个模块化工程中使用它,必须要通过Vue.use()明确地安装路由功能:
import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter);
1、先删除没有用的东西
2、components
目录下存放我们自己编写的组件
3、定义一个Content.vue
的组件
<template> <p> </p> <h1>内容页</h1> </template><script> export default { name:"Content" }</script>
Main.vue
组件
<template> <p> </p> <h1>首页</h1> </template><script> export default { name:"Main" }</script>
4、安装路由,在src目录下,新建一个文件夹:router
,专门存放路由,配置路由index.js,如下
import Vue from'vue'//导入路由插件import Router from 'vue-router'//导入上面定义的组件import Content from '../components/Content'import Main from '../components/Main'//安装路由Vue.use(Router) ;//配置路由export default new Router({ routes:[ { //路由路径 path:'/content', //路由名称 name:'content', //跳转到组件 component:Content },{ //路由路径 path:'/main', //路由名称 name:'main', //跳转到组件 component:Main } ] });
5、在main.js
中配置路由
import Vue from 'vue'import App from './App'//导入上面创建的路由配置目录import router from './router'//自动扫描里面的路由配置//来关闭生产模式下给出的提示Vue.config.productionTip = false;new Vue({ el:"#app", //配置路由 router, components:{App}, template:'<app></app>'});
6、在App.vue
中使用路由
<template> <p> <!-- router-link:默认会被渲染成一个<a>标签,to属性为指定链接 router-view:用于渲染路由匹配到的组件 --> <router-link>首页</router-link> <router-link>内容</router-link> <router-view></router-view> </p></template><script> export default{ name:'App' }</script><style></style>
我们采用实战教学模式并结合ElementUI组件库,将所需知识点应用到实际中,以最快速度带领大家掌握Vue的使用;
注意:命令行都要使用管理员模式运行
1、创建一个名为hello-vue的工程vue init webpack hello-vue
2、安装依赖, 我们需要安装vue-router、element-ui、sass-loader和node-sass四个插件
#进入工程目录cd hello-vue#安装vue-routern npm install vue-router --save-dev#安装element-uinpm i element-ui -S#安装依赖npm install# 安装SASS加载器cnpm install sass-loader node-sass --save-dev#启功测试npm run dev
3、Npm命令解释:
npm install moduleName
:安装模块到项目目录下npm install -g moduleName
:-g的意思是将模块安装到全局,具体安装到磁盘哪个位置要看npm config prefix的位置npm install -save moduleName
:–save的意思是将模块安装到项目目录下, 并在package文件的dependencies节点写入依赖,-S为该命令的缩写npm install -save-dev moduleName
:–save-dev的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖,-D为该命令的缩写把没有用的初始化东西删掉!
在源码目录中创建如下结构:
创建首页视图,在views目录下创建一个名为Main.vue的视图组件:
<template> <p>首页</p></template><script> export default { name:"Main" }</script><style></style>
创建登录页视图在views目录下创建名为Login.vue的视图组件,其中el-*的元素为ElementUI组件;
<template> <p> <el-form> <h3>欢迎登录</h3> <el-form-item> <el-input></el-input> </el-form-item> <el-form-item> <el-input></el-input> </el-form-item> <el-form-item> <el-button>登录</el-button> </el-form-item> </el-form> <el-dialog> <span>请输入账号和密码</span> <span> <el-button>确定</el-button> </span> </el-dialog> </p></template><script> export default { name: "Login", data(){ return{ form:{ username:'', password:'' }, //表单验证,需要在 el-form-item 元素中增加prop属性 rules:{ username:[ {required:true,message:"账号不可为空",trigger:"blur"} ], password:[ {required:true,message:"密码不可为空",tigger:"blur"} ] }, //对话框显示和隐藏 dialogVisible:false } }, methods:{ onSubmit(formName){ //为表单绑定验证功能 this.$refs[formName].validate((valid)=>{ if(valid){ //使用vue-router路由到指定界面,该方式称为编程式导航 this.$router.push('/main'); }else{ this.dialogVisible=true; return false; } }); } } }</script><style> .login-box{ border:1px solid #DCDFE6; width: 350px; margin:180px auto; padding: 35px 35px 15px 35px; border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; box-shadow: 0 0 25px #909399; } .login-title{ text-align:center; margin: 0 auto 40px auto; color: #303133; }</style>
创建路由,在router目录下创建一个名为index.js
的vue-router路由配置文件
//导入vueimport Vue from 'vue';import VueRouter from 'vue-router';//导入组件import Main from "../views/Main";import Login from "../views/Login";//使用Vue.use(VueRouter);//导出export default new VueRouter({ routes: [ { //登录页 path: '/main', component: Main }, //首页 { path: '/login', component: Login }, ]})
APP.vue
<template> <p> <router-view></router-view> </p></template><script>export default { name: 'App',}</script><style>#app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>
main.js
// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from './App'import router from "./router"import ElementUI from 'element-ui'import 'element-ui/lib/theme-chalk/index.css'Vue.use(router)Vue.use(ElementUI)/* eslint-disable no-new */new Vue({ el: '#app', router, render:h=>h(App)})
测试:在浏览器打开 http://localhost:8080/#/login
如果出现错误: 可能是因为sass-loader的版本过高导致的编译错误,当前最高版本是8.0.2,需要退回到7.3.1 ;
去package.json文件里面的 "sass-loader"的版本更换成7.3.1,然后重新cnpm install就可以了;
嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。
demo
1、 创建用户信息组件,在 views/user 目录下创建一个名为 Profile.vue 的视图组件;
Profile.vue
<template> <h1>个人信息</h1></template><script> export default { name: "UserProfile" }</script><style></style>
2、在用户列表组件在 views/user 目录下创建一个名为 List.vue 的视图组件;
List.vue
<template> <h1>用户列表</h1></template><script> export default { name: "UserList" }</script><style></style>
3、 修改首页视图,我们修改 Main.vue 视图组件,此处使用了 ElementUI 布局容器组件,代码如下:
Main.vue
<template> <p> <el-container> <el-aside> <el-menu> <el-submenu> <template><i></i>用户管理</template> <el-menu-item-group> <el-menu-item> <!--插入的地方--> <router-link>个人信息</router-link> </el-menu-item> <el-menu-item> <!--插入的地方--> <router-link>用户列表</router-link> </el-menu-item> </el-menu-item-group> </el-submenu> <el-submenu> <template><i></i>内容管理</template> <el-menu-item-group> <el-menu-item>分类管理</el-menu-item> <el-menu-item>内容列表</el-menu-item> </el-menu-item-group> </el-submenu> </el-menu> </el-aside> <el-container> <el-header> <el-dropdown> <i></i> <el-dropdown-menu> <el-dropdown-item>个人信息</el-dropdown-item> <el-dropdown-item>退出登录</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </el-header> <el-main> <!--在这里展示视图--> <router-view></router-view> </el-main> </el-container> </el-container> </p></template><script> export default { name: "Main" }</script><style> .el-header { background-color: #B3C0D1; color: #333; line-height: 60px; } .el-aside { color: #333; }</style>
4、 配置嵌套路由修改 router 目录下的 index.js 路由配置文件,使用children放入main中写入子模块,代码如下
index.js
//导入vueimport Vue from 'vue';import VueRouter from 'vue-router';//导入组件import Main from "../views/Main";import Login from "../views/Login";//导入子模块import UserList from "../views/user/List";import UserProfile from "../views/user/Profile";//使用Vue.use(VueRouter);//导出export default new VueRouter({ routes: [ { //登录页 path: '/main', component: Main, // 写入子模块 children: [ { path: '/user/profile', component: UserProfile, }, { path: '/user/list', component: UserList, }, ] }, //首页 { path: '/login', component: Login }, ]})
5、 路由嵌套实战效果图
图 路由嵌套效果图
这里演示如果请求带有参数该怎么传递
demo
用的还是上述例子的代码 修改一些代码 这里不放重复的代码了
第一种取值方式
1、 修改路由配置, 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符
{ path: '/user/profile/:id', name:'UserProfile', component: UserProfile}
2、传递参数
此时我们在Main.vue中的route-link位置处 to 改为了 :to,是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径;
<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定--><router-link>个人信息</router-link>
3、在要展示的组件Profile.vue中接收参数 使用 {{$route.params.id}}来接收
Profile.vue 部分代码
<p> </p>个人信息
{{$route.params.id}}
第二种取值方式 使用props 减少耦合
1、修改路由配置 , 主要在router下的index.js中的路由属性中增加了 props: true 属性
{ path: '/user/profile/:id', name:'UserProfile', component: UserProfile, props: true}
2、传递参数和之前一样 在Main.vue中修改route-link地址
<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定--><router-link>个人信息</router-link>
3、在Profile.vue接收参数为目标组件增加 props 属性
Profile.vue
<template> <p> 个人信息 {{ id }} </p></template><script> export default { props: ['id'], name: "UserProfile" }</script><style></style>
图 传参效果图
重定向的意思大家都明白,但 Vue 中的重定向是作用在路径不同但组件相同的情况下,比如:
在router下面index.js的配置
{ path: '/main', name: 'Main', component: Main},{ path: '/goHome', redirect: '/main'}
说明:这里定义了两个路径,一个是 /main ,一个是 /goHome,其中 /goHome 重定向到了 /main 路径,由此可以看出重定向不需要定义组件;
使用的话,只需要在Main.vue设置对应路径即可;
<el-menu-item> <router-link>回到首页</router-link></el-menu-item>
路由模式有两种
修改路由配置,代码如下:
export default new Router({ mode: 'history', routes: [ ]});
404 demo
1.创建一个NotFound.vue视图组件
NotFound.vue
<template> <p> </p> <h1>404,你的页面走丢了</h1> </template><script> export default { name: "NotFound" }</script><style></style>
2.修改路由配置index.js
import NotFound from '../views/NotFound'{ path: '*', component: NotFound}
3.效果图
图 404效果图
路由钩子与异步请求
beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
在Profile.vue中写
export default { name: "UserProfile", beforeRouteEnter: (to, from, next) => { console.log("准备进入个人信息页"); next(); }, beforeRouteLeave: (to, from, next) => { console.log("准备离开个人信息页"); next(); } }
参数说明:
to:路由将要跳转的路径信息
from:路径跳转前的路径信息
next:路由的控制参数
next() 跳入下一个页面
next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
next(false) 返回原来的页面
next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例
在钩子函数中使用异步请求
1、安装 Axios
cnpm install --save vue-axios
2、main.js引用 Axios
import axios from 'axios'import VueAxios from 'vue-axios'Vue.use(VueAxios, axios)
3、准备数据 : 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。
数据和之前用的json数据一样 需要的去上述axios例子里
// 静态数据存放的位置static/mock/data.json
4.在 beforeRouteEnter 中进行异步请求
Profile.vue
export default { //第二种取值方式 // props:['id'], name: "UserProfile", //钩子函数 过滤器 beforeRouteEnter: (to, from, next) => { //加载数据 console.log("进入路由之前") next(vm => { //进入路由之前执行getData方法 vm.getData() }); }, beforeRouteLeave: (to, from, next) => { console.log("离开路由之前") next(); }, //axios methods: { getData: function () { this.axios({ method: 'get', url: 'http://localhost:8080/static/mock/data.json' }).then(function (response) { console.log(response) }) } } }
5.路由钩子和axios结合图
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Vue's most detailed knowledge and notes. For more information, please follow other related articles on the PHP Chinese website!