This is a series of articles, all the exercises in this collection exist in my GitHub warehouse Vue-webpack, after I have a new understanding and understanding of the article will be the occasional correction and update. The following is a list of the currently completed:
- Webpack Journey into the Pit (i) is not the beginning of the start
- Webpack Journey into the Pit (ii) loader introduction
- Webpack Journey into the Pit (iii) Webpack.config INTRODUCTION
- Webpack Journey into the Pit (iv) sail
- Webpack Journey into the Pit (v) load the Vue Single file component
- Webpack into the Pit Tour (vi) with Vue-router to achieve spa
In the above exercise we have successfully loaded a .vue
single-file component in a format and implemented an automatic refresh with Vue.
But our ultimate goal is to implement a single-page application, this time we need to use the route manager for the development of the SPA, Vue officially provides us with an official library vue-router, and with the corresponding Chinese documents. About the contents of the people go to see themselves. Here, we only take what we need.
Vue Components
Official website for component explanation
It's Vue
very simple to define a component in, just a couple of custom labels , fill in the content and write our component, and then use the Vue.component()
to register our component to see an example of the Vue component visually.
Getting Started with components
123456789101112131415161718192021 |
<script src="Js/vue.js" ></script> <body> <div id="app" > <my-component></my-component> <!--custom labels as component names --<my-component></my-component> <!--multiplexing --</div> <script> //define and register components//In the official example use Vue.extend ({}) first to register a definition template, then reference, see a person's preferencesVue.component ("My-component", {Template"})//Create root instance//when defining and registering the component must be created before the root instance, otherwise it will be an error, because of the problem of parsing order? New Vue ({El"#app"});</script> </body> |
This is the simplest way to define a component, template
something that is written in the property: the <my-component>
style that is displayed after the custom label is rendered, which is rendered as:
1234 |
<div id="app" > <H2>hello Vue component</h2> <H2>hello Vue component</h2> </div> |
Using template tags
In the above code the contents of the components are written in the template
property, if the contents of the component continues to increase, a bunch of quotes and plus signs to splice these strings is a nightmare. So Vue introduced a template
tag (HTML5 defined, the browser does not parse the content in the default). <template> 不能用在 <table> 内
Let's look at how it's used:
123456789101112131415161718192021 |
<script src="Js/vue.js" ></script> <body> <!--use template and add selectors (use ID only)-<template id="myTemp" > <h2>this is Template </h2> <P>add ... </p> </template> <div id="app" > <my-component></my-component> <my-component></my-component> </div> <script> Vue.component ("My-component", {Template"#myTemp"//selector in the template tag defined above })New Vue ({El"#app"});</script> </body> |
You can see in the registration component that you can template
use selectors to get to the <template>
contents of our tags above. So this should be rendered as:
123456 |
<div id="app" > <h2>this is Template </h2> <P>add ... </p> <h2>this is Template </h2> <P>add ... </p> </div> |
The basic introduction of the component is here, more details please visit the official website
Vue-router
I've just had a certain understanding of Vue's components. Now let's combine the vue-router to make a dynamic switch.
The first is the installation, if you use NPM in the form of direct operation npm install vue-router --save
, you can see vue-router
, has been added to the project dependencies. Directly on ES6
the syntax to be introduced
123 |
import vue from "Vue"; import Vuerouter from "Vue-router"; Vue.use (Vuerouter); |
Start
In fact, this part vue-router
of the Chinese document has been said in very detailed. The difference here is that it uses the CommonJS
spec to install the module, and I use the import of ES6, interested to see it myself. I'm just going to get it off the other stuff.
Html:
12345678910 |
<div id="app" > <H1>hello app! </h1> <p> <!--navigation using the instruction V-link. -<a v-link="{path: '/foo '}" >go to foo</a> <a v-link="{path: '/bar '}" >go to bar</a> </p> <!--routing outside the chain --<router-view></router-view> </div> |
Javascript:
12345678910111213141516171819202122232425262728 |
//define Componentsvar Foo = vue.extend ({Template' <p>this is foo!</p> '})var Bar = vue.extend ({Template' <p>this is bar!</p> '})//router requires a root component. //For demonstration purposes, an empty component is used here, directly using HTML as the template for the applicationvar App = Vue.extend ({})//Create a router instance//Create instances can be customized by passing in configuration parameters, to keep it simple, use the default configuration herevar router = new Vuerouter () //define Routing rules//Each routing rule should be mapped to a component. The "component" here can be a use of vue.extend//Create a component constructor, or it can be a component option object. //We will explain the nestingRouter.map ({'/foo ': {Component:foo},'/bar ': {Component:bar}})//Now we can launch the app! The //router creates an instance of the APP and mounts to the element that the selector #app matches. Router.start (APP,' #app ') |
I personally feel that this part is still very well understood, the official also gave an online sample application. It's a good show of its routing switch.
A simple introduction to this, the most important part of the following is to see how to combine our defined .vue
single-file components.
First look at our file directory structure:
Defining Routing Rules
The main thing main.js
is The changes are explained directly in the document:
12345678910111213141516171819202122232425262728293031323334 |
//Introducing Vue and Vue-routerimport vue from "Vue"; import Vuerouter from "Vue-router"; Vue.use (Vuerouter);//Introduction Components! Syntax for direct use of ES6Import index from './components/app.vue '; Import list from './components/list.vue '; Import Hello from './components/hello.vue '; //Turn on Debug modeVue.config.debug =true;//New Vue (APP);//This is the last one used, create a new Vue instance, now you don't need to use vue-router. //router requires a root component. var App = Vue.extend ({});//Create a router instancevar router = new Vuerouter (); //Each routing rule should be mapped to a component. The "component" here can be a component constructor created using Vue.extend, or it can be a component option object. //We will explain the nestingRouter.map ({//define route mappings'/index ': {//access address Name' index ',//define the name of the route. Easy to use. Component:index,//referenced component name, corresponding to the component imported using ' import ' above//component:require ("Components/app.vue")//can also be used directly in this way is also no problem. But there will be no import centralized so intuitive},'/list ': {Name' list ',Component:list}); Router.redirect ({//define global redirection rules. Global redirection is performed before the current path is matched. ' * ': '/index '//redirect any unmatched path to/index });//Now we can launch the app! The //router creates an instance of the APP and mounts to the element that the selector #app matches. Router.start (APP,' #app '); |
In index.html you need to have components for render matching, as follows
123 |
<div id="app" > <router-view></router-view> </div> |
Now when we run the npm start
entry http://localhost:8080/
it will automatically jump to and http://localhost:8080/#!/index
read the contents.
Implementing a routing Jump
Main app.vue
out of the content to explain, the content is: ( list.vue
inside the content self-setting to see it)
1234567891011121314151617181920212223242526 |
<template> <div> <h1> Name: {{name}}</h1> <H2>{{age}}</h2> <button @click="Golist" > $route. Router.go view </button> <a v-link="{name: ' list '}" >v-link View list </a> <a v-link="{name: ' index '}" > Go home </a> </div> </template> <script> Export Default {//Here is the official wording, the defaults are exported, ES6 Data () {//es6, equivalent to Data:function () {}return { //must use this form in order to create a single scope Name"GUOWENFH",Age"very"}},methods: {golist () {//method, define the routing jump, note that this must be used here, or errorThis . $route. Router.go ({name:"List"}); }}}</script> <style></style> <!--style, or just look at the source . |
Because of the self-refresh, switch directly to the browser.
Click on the above v-link
, and router.go
the way you can jump to the list
defined route. ( observe the changes in the browser address bar ) Here we use {name:"list"}
, the use { path: ‘/list‘ }
will have the same effect.
Referencing Vue components
In the first small point we saw the use of components within the page, the second small point learned to vue-router
develop routing rules.
After looking at these two places, we spread our minds and should be able to comprehend by analogy the idea of nesting other components in the page.
We create one hello.vue
that is free of content. Now if we want to app.vue
load it in, then we just need to use it in app.vue
(in import hello from "./hello.vue"
fact, this achieves the effect of using require two steps.) Introduction of Assignment).
After introduction, you only need to register as follows:
123456 |
Export Default { // other on components:{Hello//If there are more components, only need to in the case of import, separated by commas, continue to register just fine }} |
Finally app.vue
, add this pair of custom tags in, you can implement the hello.vue
content in the load.
The nesting of components is so, very simple description is done, but how to get away from the components, in the work to accumulate reusable components is what we really need to think about.
So first here, about the communication between the components of the problem, to stay in the future slowly understand.
Routing nestingOr just the code and directory structure, we have implemented the nesting between components, but sometimes do not want the component to load directly, but only after the user clicks on the page, it is necessary to use the route nesting.
In order to be lazy, it is used directly here hello.vue
. Implementing a nested routine consists mainly of the following steps:
The first step: set up a nested routine by the rule:
Look at main.js
This part of the code:
123456789101112131415 |
Router.map ({ '/index ': { name:' index ', component:index, //Set a sub-route under/index subroutes:{ When matching to/index/hello, the '/hello ' is rendered in the <router-view> of index: {name:' Hello ',//optional, Primarily for ease of use //A Hello component Component:hello}}}); |
Step two: Add in the component<router-view>
Explanation from the official website: The <router-view>
component used to render the match, which is based on Vue's dynamic component system, so it inherits many of the features of a normal dynamic component.
will be <router-view>
written in app.vue
the <template></template>
label.
Step three: Write the jump path
Or is it in app.vue
:
123 |
<a v-link="{name: ' index '}" > Go home </a> <!--Clicking on these two tabs will result in a transition within the page-- <a v-link="{name: ' Hello '}" > Nested routing </a> |
, switch to the browser, click on it to 嵌套的路由
let hello.vue
in the show, where directly used v-link
to achieve jump (know why to write name it.) If you use path it will be { path: ‘/index/hello‘ }
--. ), of course router.go
. (Note that when you click on two different text, the change of the address bar, and the toggle of the display content)
Attention:
In my source code is defined in the <style scoped></style>
label style, please note that scoped
the use, it means that the style
style defined in the current component will only play an effect, not to affect the global CSS style.
The simplest understanding should be:
scoped
styles in all components of the property are not written, and vue-loader
have a global scope after compilation. Equivalent to sharing one copy of the css
style sheet.
Instead, the style defined in the component that wrote the attribute has a separate scope. It is equivalent to removing a stylesheet that introduces a common one css
, but has a single copy css
of the style sheet.
All right, here we go. It's a little messy, see you next time
Webpack into the Pit Tour (vi) with Vue-router to achieve spa