current position:Home>[Vue] how to install Vue scaffold and create scaffold project_ ten
[Vue] how to install Vue scaffold and create scaffold project_ ten
2022-06-24 09:56:38【Elegant roasted sweet potato】
Catalog
1. Problems in front-end project structure
3. The benefits of using scaffolding
Two . Scaffold folder structure
1. The only complete HTML The page is split into three parts : public/index.html
2. Page components : src/views Under the folder
3. Router object : src/router/index.js
4. Global component or subcomponent : src/components Under the folder
3、 ... and . ES6 Modular development
Four . Avoid style conflicts between components
6、 ... and . Use scaffolding to create a vue Project instance
Expand :this Judge —8 Species direction
️ summary : Knowledge points extraction
【 Previous review 】 vue How to realize SPA Single page application _09
One . vue The scaffold
1. Problems in front-end project structure
The modern front-end project structure is very complex ! If anyone is allowed to define the folder structure of the project , consequence , There are great differences between the project and the project structure ! That is, it is not easy to maintain , It is also not convenient for developers to quickly adapt to !
2. How to solve
VUE The government has issued a standardized vue Project structure ! All use vue Framework development projects should follow this standardized project structure !—— The scaffold
3. The benefits of using scaffolding
Almost all use vue Project done , The folder structure is almost identical ! Developers can adapt to new projects very quickly !
4. When to use scaffolding
No matter what framework you learn in the future , Find the scaffold first .
5. How to use scaffolding
2 Step :
(1). Download and install a command line tool that can repeatedly generate scaffold code : ( Old hen )
a. explain : Just install it on your computer once , You can repeatedly create a scaffold project structure for multiple different projects
b. how : 2 Step :
1). First configure npm Domestic Taobao mirror , Download and install from domestic servers : fast
2 Choose one :
a. npm config set registry http://registry.npm.taobao.org
↓ ↓ ↓ ↓
npm To configure Set up Warehouse
After execution , Confirm whether the setting is successful : npm config get registry
↓ ↓ ↓ ↓
npm To configure get Warehouse
See the return Taobao image , It means success !
b. alternative : If the previous step goes wrong ! You can choose this step :
npm i -g cnpm --registry=http://registry.npm.taobao.org
Confirm whether the installation is successful : cnpm -v
Seeing the version number indicates success !
2). Download and install command line tools : vue/cli, 2 Choose one
a. use npm install : npm i -g @vue/cli
npm install overall situation command line interface
install global command That's ok Interface
// if FEXIST error , You can enter the path in the error prompt , The default is :
C:\Users\ The user name to log in to the operating system \AppData\Roaming\npm\node_modules
Delete @vue Folder
b. alternative : If npm error , It can be replaced by : cnpm i -g @vue/cli
notice : + @vue/[email protected], Description installation successful
(2). Use scaffolding to create a standardized set of... For this project vue Project structure :
a. First find the folder where you want to create the project : Find the folder directory in the operating system where you want to create the project , Then enter... In the address bar cmd, Press enter
b. Input vue create Custom project name
1). Vue CLI v4.5.8
? Please pick a preset: (Use arrow keys)
Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
> Manually select features
2). ? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
() Choose Vue version // choice vue Version of scaffold
> (*) Babel // Transcoder : Will be fashionable ES6, ES7 The grammar of , Most browsers know ES5 grammar
() TypeScript
() Progressive Web App (PWA) Support // Progressive type Web Applications
(*) Router // VueRouter,SPA The core components of the application , namely vue-router(vue Routing component )
() Vuex // vuex(vue State management mode )
(*) CSS Pre-processors // CSS The preprocessor ( Such as :less、sass)— Support Scss grammar , No choice
() Linter / Formatter // Code style checking and formatting tools ( Such as :ESlint) Strict requirements , Not recommended
() Unit Testing // unit testing (unit tests)
() E2E Testing // e2e(end to end) test
3). ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) n
Vue There are two modes of routing :
hash Pattern : Default : #/ Relative paths —— No server-side support is required to use .
history Pattern :/ Relative paths —— You need to configure the home page redirection mechanism on the server side !
4). ? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys) In dedicated config files
> In package.json
5). ? Save this as a preset for future projects? (y/N) N
c. success : Successfully created project xzvue.
(3). Running scaffolding projects :
a. Delete... From the project .git Folder ( Can keep , If you don't use vscode Conduct git edition ( Code ) management , Deleting )
b. vscode Open the newly generated scaffold project folder
c. stay vscode in , Right click on the package.json file , Select Open... In the integration terminal
d. In the pop-up terminal window : Input npm run serve
If an error is reported : Cannot be “npm” Item identified as cmdlet...
You can right-click on my computer -> attribute -> Advanced system setup -> environment variable -> In the system variable list below -> double-click path-> newly build ->C:\Users\ user name \AppData\Roaming\npm( The user name is changed to the user name when you log in to the current operating system )
e. success : DONE Compiled successfully in 8922ms
f. npm run serve, Started a temporary server , preservation vue All compiled pages . Address : App running at:
- Local: http://localhost:8080/
therefore , stay vscode in , Hold down ctrl Click this link address , Open the browser
Two . Scaffold folder structure
1. The only complete HTML The page is split into three parts : public/index.html
The only complete HTML page ( Split into three , The runtime is combined )
(1). problem : index.html There is no <router-view> There is no new Vue()
(2). reason :
a. vue The author thinks that , stay index.html Should not contain any js Code !
b. The author thinks that ,vue Everything in is a component , even <div id="app"> It's also a component . therefore , Be sure to will <div id="app"> Also in a separate component file .
(3). solve :
The only complete HTML The three parts of the page are divided into :index.html、App.vue、main.js
a. original index.html Medium new Vue() etc. js Code , All stored in src/main.js In file
b. original index.html Medium <div id="app">, All stored in src/App.vue In file
<div id="app"> <router-view></router-view> </div>
c. In use npm run serve When compiling the entire project :
1). use App.vue Medium <div id="app"> Instead of index.html The space temporarily occupied in the <div id="app">
2). take main.js Medium new Vue() etc. js The code is reintroduced back to index.html On the page .
2. Page components : src/views Under the folder
Page components ( There are several pages in the project , It includes several page components )
(1). src/views Under the folder
(2). problem :
a. stay js Write the name of the component in the file template when , No hint , A lot of pain !
b. css Where to write ?
(3). solve : Vue A new file format is created in : .vue file
a. Vue Each component of , All have to be created as a .vue file
b. Every .vue The document contains three parts :
1). Specially write HTML The area of the code snippet : <template>
If you want a hint , Need to install vscode Plug in for vetur
2). An area dedicated to writing component objects : <script></script>
export default {
// The content of the page component
}
3). Specially write CSS Area of style : <style></style>
3. Router object : src/router/index.js
Router object : src/router/index.js, It also contains a routing Dictionary routes And router objects router.
4. Global component or subcomponent : src/components Under the folder
3、 ... and . ES6 Modular development
1. problem
Obviously router.js You need to use index Components and details Components , But we have to index Components and details Components lead to index.html In the web page !—— The disorderly
2. solve
In the scaffold ES6 Modular development ! You can make direct references between modules !—— intuitive , concise
for instance router.js You need to use index Components and details Components , You can directly introduce , There is no need to go around index.html Web page reference
3. how
How to realize modular development ,2 Step :
(1). Turn all components into module objects : ( Only modules can be introduced , So first it must be a module )
a. Default : One without js Of .vue file , The default is a module object .
yes , we have .vue file , It's not js Of , And there are .vue There's no document css, For example, there are .vue file ( Components ) Only html(template). A module object does not necessarily have js or css, Only html(template) Of .vue The document is a vue The default module object
b. If one .vue The document contains js Component object , You have to use export default {} After throwing the module object , To let others introduce !
(2). If a component / In module , Another module is required The content of , You can use import Introduce other modules , For your own use
import Custom variable name from " Relative paths "
From the file in the specified path
Introduce a module object
Save in a custom variable name

Expand :.vue The suffix of the module file can be omitted
Use import When introducing other modules , If the module file is .vue ending , You can omit .vue Suffix name , Such as :import Detail from ”../views/detail.vue”, among ,.vue Omission ;
If the module file is index.js, You can omit index.js, Such as :import router from “../router/index.js, among ,index.js Omission . As long as it is an introduction module , The file under the folder is index.js, All can be omitted ( Just under the folder js File is index.js, You can omit ). You can view learning node.js Folder module
About when to use ../ And ./ —— See if it is necessary to go up , Use if necessary ../ For the same level, use ./
Four . Avoid style conflicts between components
1. problem
stay Different page components The same selector used in defines different css style , result , Only one of them css The style can be retained ! There was a conflict !
2. principle
All components of css Code , It will eventually be packaged and compressed into a css file . Of all future components css, It's actually in a file . If two identical selectors appear in a file , Only the latter can take effect !
3. solve
2 Kind of :
(1). automation ( Not everything , Low efficiency ):
a. <style scoped>
( Current component ) Within the scope of
b. Meaning for : Add the following css Styles are limited to elements within the current component ! Elements of other components are not available
c. principle :
1). scoped It will automatically add the same random custom attribute name to each element of the current component .< Elements data-v- Random name >
2). Automatically add an additional condition to the end of all selectors in the current component :
Other selectors [data-v- Random name ]
result : Only with data-v- Only elements with random names can use this selector
3). scoped You can guarantee that the random names of each component are different ! It implements a component , You cannot use styles from other components !
(2). Manual solution ( universal ):
a. how : 2 Step :
1). Every time you create a component , On the only parent element of the component , Define a special class name ( Try to be the same as the component name )
2). stay <style> All selectors in this component , Must be ". The component name " start
b. Example :
Home.vue
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<h1> welcome {
{uname}}</h1>
</div>
</template>
<script>
export default {
data(){
return {
uname:" East east "
}
}
}
</script>
<style>
.home>h1{
background-color:red;
color:yellow;
}
</style>
Running results :
About.vue
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<style>
.about>h1{
background-color:green;
color:#fff;
}
</style>
Running results :
Expand : Use v-html When binding element content , The style of the element content needs to use overall situation
<style>
Elementstay Single file component in ,
scoped
The style will not be applied inv-html
Inside , Because that part HTML Has not been Vue Template compiler processing . If you wish to targetv-html
Content Settings with scope CSS, You can replace it with CSS Modules Or use an extra global<style>
The element is set manually similarly BEM Scope policy .
Reference resources vue Official website v-html:https://cn.vuejs.org/v2/api/#v-html
5、 ... and . Lazy loading
1. problem
The biggest problem with single page applications : Home page loading is extremely slow !
2. reason
Because the single page application defaults to the first request , All page components must be downloaded to the local client !
3 principle
npm run serve when ,vue Scaffolding will remove all .vue The code of the file is packed and compressed into one js In file , Then introduce the only complete index.html In file . therefore , This one contains all the code js The files will be big !
4. solve
Lazy loading , What you need , Just load what ; It doesn't need anything , It doesn't load !2 Kind of :
(1). Asynchronous deferred loading ( Scaffold default ):
a. What is? : First download the home page , Other page components , It adopts the method of asynchronous delayed download at the bottom , Quietly download to the client .
Don't put other codes except the home page for the time being import In process !
Define in the routing dictionary , Only when a user accesses a component , To dynamically introduce this component .
src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from "../views/Index"
Vue.use(VueRouter)
const routes = [
{
path: '/',
component: Index
},
{
path: '/details/:lid',
// Don't put Details.vue Introduce projects
// Only when the user accesses details when , Only then Details Components are introduced into the project
// and webpackChunkName: Is indicating , take Details.vue The file is packed and compressed into a single file . The file named details
component: () => import(/* webpackChunkName: "details" */ '../views/Details.vue'),
props:true
}
]
const router = new VueRouter({
base: process.env.BASE_URL,
routes
})
export default router
b. advantage : compromise : That is, it does not affect the loading speed of the home page , And it can ensure that when switching pages in the future , Only switch quickly on the client
c. shortcoming : In case the user doesn't want to see the rest of the page , Download it, too , A bit of a waste of traffic !
Although it will not be downloaded on the first screen details.js, But it will download asynchronously in the background details.js, Steal traffic !
(2). Real lazy loading :
Thorough lazy loading
a. If the user does not visit other pages , Do not download the contents of other pages at all
b. how : stay vue Add a configuration information to the scaffold :
1). stay vue Create in the root directory of the scaffold project vue.config.js
2). stay vue.config.js Add the following fixed configuration information to , It is forbidden to download other components in advance
module.exports = {
chainWebpack: config => {
config.plugins.delete("prefetch")
// Delete index.html Begin with prefetch Attribute link, Do not asynchronously download page component files that are not needed temporarily
},
}
c. result : Content of other page components except the home page , Don't download in advance at all . Only when the user point is connected , When accessing a page , To temporarily download the contents of this page component
d. problem : Because when a user visits a page , Temporarily download the contents of the page , The loading speed is slightly slow .
Questions about lazy loading
Your doubts
Someone will ask. , Only when the user point is connected , When accessing a page , To temporarily download the contents of this page component , This is similar to multi page application ( After downloading , Before you can take it to see ) There is no difference ?
Personal understandingFirst , The download is a clip , Not the whole page , This is much smaller than the entire page requested by a multi page application , secondly , A thorough lazy load only needs to be downloaded once , Save to client , You can look at it again and again in the future , The previous multi page application is not good , Multi page applications are not cached . therefore , The temporary download is a little slow , But compared with multi page applications, the advantages are still obvious
6、 ... and . Use scaffolding to create a vue project
Let's introduce , In the future vue Required tools for scaffolding project axios, How to install 、 Configure and introduce components
install and configure axios:
(1). Scaffold is not equipped with by default axios
(2). install : npm i -save axios
Installed inside the current project
(3). To configure :
a. stay main.js in , new Vue() Before We need to configure
b. introduce axios modular
import axios from "axios" // node_modules in
c. To configure axios The basic path :
axios.defaults.baseURL="http:// The base address of the server-side interface "
d. problem : Used in almost all components axios
Premise : Whether it's new Vue(), still Vue.component(), still export default {}, In fact, the essence is Vue type A kind of Sub object
solve : therefore axios Should be placed in Vue In the prototype object of type !
Vue.prototype.axios=axios
(4). Use : Anywhere in any component , All available :
this.axios.get/post(...).then(result=>{ ... result.data ... })
Complete folder structure of scaffold project , As shown in the figure below :
vue The source code of each component of the project is as follows :
️ public/index.html The only complete html page
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
️ src/App.vue The only root component ( Summarize all components )
<template>
<div id="app">
<my-header></my-header>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
️ src/components/MyHeader.vue Header components —— Global components
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
</template>
<style>
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
️ src/views/Home.vue Homepage component
<template>
<!-- Specially written components HTML Content -->
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<h1> My first scaffolding project !</h1>
<h2> My user nickname :{
{ uname }}</h2>
<h3> user ID:{
{ uid }}</h3>
<button @click="search"> my CSDN Personal home page </button>
</div>
</template>
<script>
// Specifically contains component objects
export default {
data() {
return {
uname: " Elegant roasted sweet potato ",
uid: "sunyctf",
};
},
methods: {
search() {
alert(" Welcome to visit CSDN!");
window.location.href = `https://blog.csdn.net/sunyctf`
},
},
};
</script>
<style>
/* Introducing external CSS file */
@import url(../assets/css/home.css);
</style>
️ src/views/About.vue About page components
methods: {
search() {
alert(" Welcome to visit CSDN!");
window.location.href = `https://blog.csdn.net/sunyctf`
},
},
};
️ src/main.js Project entrance js file
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from "axios"
import MyHeader from "./components/MyHeader.vue"
Vue.component("my-header",MyHeader);
axios.defaults.baseURL="http://localhost:8080";
// take axios Class libraries are added to vue In the prototype object of , So every page can use
Vue.prototype.axios=axios;
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
️ src/router/index.js Router files
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
// Lazy loading
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
routes
})
export default router
️ src/assets/css/home.css Home page style file
/* Solutions to avoid style conflicts between components :
* 1). Every time you create a component , On the only parent element of the component , Define a special class name ( Try to be the same as the component name )
* 2). stay <style> All selectors in this component , Must be ". The component name " start
*/
.home>h1 {
background-color: red;
color: yellow;
}
.home>button {
width: 300px;
height: 50px;
border-radius: 5px;
background-color: aqua;
border: 0px;
font-size: 21px;
color: white;
font-weight: bolder;
}
️ src/assets/css/about.css About page style files
/* Solutions to avoid style conflicts between components :
* 1). Every time you create a component , On the only parent element of the component , Define a special class name ( Try to be the same as the component name )
* 2). stay <style> All selectors in this component , Must be ". The component name " start
*/
.about>h1 {
background-color: aqua;
color: coral;
}
Running scaffolding projects :
Page effect preview :
️ Be careful :Vue Your router uses an anchor address , As the relative address of client navigation
for example :http://127.0.0.1:8080/index.html#/ Relative paths Router object router Monitoring is # After the address
Expand :this Judge —8 Species direction
this 8 Species direction : Judge this, Don't look at the definition ! Just look at the call !
️ 1. obj.fun() this->obj
️ 2. fun() or (function(){ ... })() or Most callback functions or Timer Functions this->window
️ 3. new Fun() this->new New object being created
️ 4. Type name .prototype. There is a common way =function(){ ... } this-> Who will call in the future refers to who , The same as in the first case
️ 5. DOM or jq In the event handling function of this-> Currently triggering the event DOM Element object
If you need to use a simplified version of the function , must $(this)
️ 6. In the arrow function this-> In the external scope of an arrow function this
️ 7. jQuery.fn. Custom function =function(){ ... } this-> Call this custom function in the future . Before jQuery Sub object , No more $(this)
️ 8. new Vue() in methods Of the functions in this-> At present new Vue() object
️ summary : Knowledge points extraction
1. MVVM: Interface View+ Model Model+ Model view ViewModel
2. Vue Binding principle : Accessor properties + fictitious DOM Trees
When a variable is modified : The accessor property issues a notification , fictitious DOM The tree scans and updates only the affected elements
3. fictitious DOM Advantages of trees :
(1). Small : Only elements that can change .
(2). Traversal search fast
(3). The modification efficiency is high : Modify only the affected elements .
(4). Avoid duplicate coding : Sealed DOM Add, delete, modify and check the code
4. Vue function 3 Step :
(1). First create an enhanced version of the interface :
a. The entire interface must be contained under a unique parent element :
Usually <div id="app">
b. The content of elements that may change is used { { Custom variable name }} Mark
c. The element that triggers the event uses @click=" Custom processing function name " Mark
(2). To create a new Vue() object , among el: Point to new Vue() The area of the page to monitor
(3). stay new Vue() The model object is defined within the object data and methods
a. All variables required by the interface are placed in data in
b. All event handling functions required by the interface are placed in the methods in
5. summary : Binding syntax +13 Instructions
(1). If the content of an element needs to change automatically with the variable : { {}}
(2). If the attribute value of an element needs to change automatically with the variable : :
(3). Controls the display and hiding of an element : v-show // Use display:none Hidden elements
(4). Control the display of two elements by selecting one from two : v-if v-else // Hide elements by deleting elements
(5). Multiple selection of multiple elements for display : v-if v-else-if v-else
(6). As long as multiple elements of the same structure are generated repeatedly to form a list : v-for :key=" Unique identification "
emphasize : Why do you have to add :key="i"? Add a unique identifier to each copy of the element . When modifying the value of an element in the array , Avoid rebuilding the entire list , Just modify one DOM Just copy the element ! Improve modification efficiency .
(7). Just bind the event : @ $event
(8). Prevent users from seeing { {}}: v-cloak and v-text
(9). Just bind the original HTML Snippet content : v-html
(10). If the content of the element is bound only once when it is first loaded , It won't change after : v-once
Optimize : Reduce virtual DOM Number of elements in the tree .
(11). Protect... In content { {}} Not compiled : v-pre
(12). In the future, just want to get the value or status of the form element : v-model
6. Binding style :
(1). It is necessary to modify a css attribute , Just bind style:
a. < Elements style=" Fixed style " :style="{css attribute : Variable name , ...}"
data:{
Variable name :css Property value
... : ...
}
b. < Elements style=" Fixed style " :style=" Variable name "
data:{
Variable name :{
css Property name : Property value ,
... : ...
}
}
(2). Just batch modify multiple of an element css Property is bound class
a. < Elements class=" Fix class" :class="{class name : Variable name , ...}"
data:{
Variable name :true or false,
... : ...
}
b. < Elements class=" Fix class" :class=" Variable name "
data:{
Variable name :{
class name :true or false,
... : ...
}
}
7. As long as you want to automatically perform some initialization operations on elements when the page is loaded, use custom instructions :
(1). Add custom instructions :
Vue.directive(" Custom directive name ",{
inserted(domElem){
Yes domElem perform DOM operation
}
})
(2). Use custom instructions :
< Elements v- Custom directive name >
8. In the future, as long as an attribute value is dynamically calculated according to the values of other variables, the calculation attribute :
< Elements >{ { Compute properties }}</ Elements >
new Vue({
el:"#app",
data:{...},
methods:{...},
computed:{
Computed attribute name (){
The calculation process
return The result of the calculation is
}
}
})
9. Use the filter when you want to process the original value of the variable before displaying it to the user :
Vue.filter(" Filter name ",function(oldVal, Custom parameters ,...){
return New value after machining
})
< Elements >{ { Variable | filter ( Argument value , ...) | ... }}</ Elements >
10. As long as vue Sent in ajax request , Just use axios
axios.defaults.baseURL=" The common base address part of the server-side interface "
axios.get(
" The relative path of the server-side interface address ",
{
params:{ Parameter name : Parameter values , ... }
}
).then(result=>{
... result.data...
})
or
axios.post(
" The relative path of the server-side interface address ",
" Parameter name 1= Parameter values 1& Parameter name 2= Parameter values 2&..."
).then(result=>{
... result.data...
})
emphasize : stay vue Internal use axios,then You must use the arrow function , keep then Inside this With the outside this Agreement , They all point to the present new Vue() object
11. vue Life cycle 4 Stages 8 A hook function
beforeCreate(){ ... }
(1). establish (create)
created(){ ... }
beforeMount(){ ... }
(2). mount (mount)
mounted(){ ... Often send... Here ajax request ... }
beforeUpdate(){ ... }
(3). to update (update)
updated(){ ... }
beforeDestroy(){ ... }
(4). The destruction (destroy)
destroyed(){ ... }
12. As long as you want to reuse a separate functional area, use components :
(1). Defining components
Vue.component(` Component tag name `,{
template:`HTML Content fragment `,
data(){ return { Variable } },
// The rest and new Vue() Exactly the same
})
(2). stay HTML Using custom components
< Component tag name /> Or double labeling
(3). principle : new Vue() Scan to custom component label ,
a. Component's template Medium HTML Content replaces... In the page < Component labels > Location .
b. And create a miniature version for this small area vue Type object .
1). Invoke component's data() Function to create an exclusive copy of the data object for the current component copy .
2). Introduce... In the component object methods And other contents into the copy of the current component object
13. Component development :
(1). step :
a. Get the page and divide the functional area first
1). From top to bottom , Divide areas according to different functions
2). Divided by reuse
b. Create separate for each component .js file , It contains a component object and its contents
c. Bring all components into a unique and complete html On the page , And in <div id=”app”></div> Add parent component label to .
(2). Runtime :
a. new Vue() scanning <div id=”app”>, Found parent component label , Create and replace parent components
b. The parent component scans its internal template Content , Create and replace subcomponents
(3). Three components :
a. The root component : new Vue()
b. Global components : Vue.component(...)
c. Child components : 3 Step
1). var Sub component object name ={
The content must meet the requirements of the component
}
The sub component object name must be hump named
2). In the parent component object :{
... ...
components{ Sub component object name , ... ,... }
}
The sub component object name must be hump named
3). Parent component template of use < Subcomponent tag name /> Introduce sub component content
components The hump name of the sub component object name will be automatically translated into - Separate
therefore , When using subcomponent labels , Use - Separate multiple words
(2). Transfer parameters between components : Father to son
a. Parent component to :
< Child components : Custom attribute names =" Parent component variable ">
b. The sub assembly takes :
props:[" Custom attribute names "]
result : In subcomponents ,props Medium " Custom attribute names " And sub components themselves data The usage of variables in is exactly the same !
14. SPA—— Single page application
(1). 3 Step :
a. First create the only complete HTML page
1). contain vue Basic page structure
<div id="app"> new Vue({el:"#app"})
2). Introduce all necessary files and components
vue-router.js, Other pages or component files , router.js The file where the router object is located
3). <div id="app"> of use <router-view/> Leave space for future page components
b. Then create a separate file for each page component . Each page component is actually a sub component
c. establish router.js file , Create router objects
1). Create a routing dictionary object :
var routes=[
{path:"/", component: Home page component object name },
{path:"/ Relative paths " , component: Other page component object names },
{path:"*", component: 404 Page component object }
]
2). Create router objects , And transfer the routing dictionary object into the router object
var router=new VueRouter({ routes })
3). take router Objects are added to new Vue() in
Back to the only complete HTML On the page : new Vue({ el:"#app", router })
(2). Global components such as page headers :
a. Create a separate file to save the contents of the header component
b. Use Vue.component("my-header",{ ... }) Create the header as a global component
c. In the only complete HTML The header component file is introduced into the page
d. Use header component labels <my-header/>: 2 Kind of :
1). If all pages have a uniform header :
Put it in the only complete html On the page <router-view> Above the outside
2). If some pages have headers , Some pages have no headers :
Just put it in the component that needs the page header template in
(3). Routing jump : 2 Kind of :
a. html in : <router-link to="/ Relative paths "> Text <router-link>
b. js in : this.$router.push("/ Relative paths ")
(4). Route parameters :
a. Modify the routing dictionary :
{path:"/ Relative paths /: Custom parameter name ", component: Page component object , props:true}
b. When jumping :
<router-link to="/ Relative paths / Parameter values "
or
this.$router.push("/ Relative paths / Parameter values ")
c. The next page follows :
1). props:[ ' Custom parameter name ' ]
2). Can be " Custom parameter name " As a binding or in a program
15. install vue The scaffold :
(1). Set up npm By default, the domestic Taobao image warehouse is used :
npm config set registry http://registry.npm.taobao.org
alternative : npm i -g cnpm --registry=http://registry.npm.taobao.org
(2). Install tools that can repeatedly generate project scaffold code :
npm i -g @vue/cli
alternative : cnpm i -g @vue/cli
(3). npm run serve
start-up vue Scaffolding project
(4). Open the browser , Address field input : http://localhost:8080
16. Scaffold folder structure :
(1). The only complete HTML page : One into three :
a. public Folder
1). picture img Put the folder in public Under the folder
2). The third party css Compressed version and third party js The compressed versions of are placed in public Under the folder
3). The only complete HTML file index.html in ,head The introduction of third-party css and js
b. src/App.vue
1). <template> Only common header components and <router-view>
2). <style> The following contains the public information that all web pages need to use css style , such as css Reset code
c. src/main.js
1). import introduce App.vue,router,axios, And other global components
2). Turn the global component object into a real global component : Vue.component( " Component tag name ", Global component object )
3). To configure axios And put it into the prototype object :
axios.defaults.baseURL=" Server side basic path "
Vue.prototype.axios=axios;
(2). Create... For each page .vue Component files , All put in src/views Under the folder . Every .vue In file :
a. <template> tag , Contains the... Of this page HTML Content
b. <script>export default{ ... }</script> That contains the component object js Content .
c. <style> The tag contains... That is used only in this page component css
d. <template> Medium HTML Content and <script>export default{...}</script> Medium js Content , It's exactly the same way as what I said four days ago , binding , Instructions , function , Life cycle ,axios Requests, etc. are the same . How to use it four days ago , How to use it here .
(3). Routing dictionary and router object , stay src/router/index.js In file
a. only import Home page component object , Don't introduce other page components too early
b. Home page component in routing dictionary : { path:"/", component: Home page component object }
c. The rest of the page components are lazy loaded :
{
path: '/ Relative paths ',
component: () => import(/* webpackChunkName: " Component name " */ '../views/ Other page components .vue')
}
(4). Global components are placed in src/components Under the folder , Each global component .vue In file . however , The global component must be in main.js introduce , And use Vue.component() Into a real global component , In other components HTML Use in .
(5). Runtime : Router router Object to monitor browser address bar path changes , And find the corresponding page component content , Replace App.vue Medium <router-view>, then main.js Then the page containing the page content to be loaded App.vue Component content , Replace with the only complete index.html Hollow <div id="app"> Location .
17. Avoid style conflicts between components :
(1)<style scoped>
(2)<template>
< Component parent element class=" Component name ">
</template>
<style>
. Component name > Child Selector { ... }
</style>
18. watch+ Event modifier + Shake proof :
(1). When you want to perform an operation automatically as soon as the variable changes :
data(){
return { Variable : value }
},
watch:{
Variable (){
What to do
}
}
(2). Event modifier :
@ event .13 Press enter to execute
@ event .stop To prevent a bubble
@ event .prevent Blocking default behavior
(3). Shake proof :
data(){
return {
... ,
timer:null
}
},
methods:{
To find the way (){
if(this.timer!=null){
clearTimeout(this.timer)
}
this.timer=setTimeout(()=>{
Formal lookup operations
}, Waiting time )
}
19. Lazy loading :
(1). Asynchronous deferred download :
src/router/index.js
// Don't import Details from "../views/Details"
const routes=[
...
{
path:"/details/:lid",
component: () => import(
/* webpackChunkName: "details" */
'../views/Details.vue'
),
props:true
]
(2). Completely lazy loading :
Project root creation vue.config.js
module.exports={
chainWebpack:config=>{
config.plugins.delete("prefetch")
// Delete index.html Begin with prefetch Attribute link, Do not asynchronously download page component files that are not needed temporarily
},
}
If this article 【 article 】 It helps you , I hope I can give 【 Juvenile wooden fish 】 Order one Fabulous , It's not easy to create , Compared with the official statement , I prefer to use 【 Easy to understand 】 To explain every point of knowledge with your writing , If there is a pair of 【 The front-end technology 】 Interested little cute , You are welcome to pay attention to ️️️【 Juvenile wooden fish 】️️️, I will bring you great 【 Harvest and surprise 】!
copyright notice
author[Elegant roasted sweet potato],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240832077470.html
The sidebar is recommended
- Fasthttp: go framework ten times faster than net/http (server)
- The difference between preload and prefetch and how to optimize in webpack projects
- Several ways of calling methods to transfer parameters in react render
- Axios usage
- LabVIEW finds prime numbers in an array of n elements
- Elementui form custom regular expression validation text box
- Export markdown to HTML, PDF with browser
- Experience summary of typescript transformation process of old vue2.x projects
- Front end development uses graphql -- vue3 uses graphql
- JS to get the last element of the array
guess what you like
About Axios request - delete method
The salon for the first anniversary of the open source of oasis, an ant interactive graphics engine, is coming. On February 26, we will see you in the live studio!
Best practices for cookie notification
How does HTML5 implement live streaming? It's worth learning!
Record webpackdemo configuration
Android studio uses iconfont Ali vector icon library
HttpMediaTypeNotSupportedException: Content type ‘application. yml/json; charset=UTF-8‘ not supported
CSS notes
Nginx enables geoip2 module to realize national city identification - the road to dream
Database to query the quantity of books lent in this month. If it is higher than 10, it will display "more than 10 books lent in this month". Otherwise, it will display "less than 10 books lent in this month"
Random recommended
- Baidu map API User Guide - Javascript API | JavaScript API GL | JavaScript API Lite
- [javascript question brushing] tree - verify binary search tree, leetcode 98
- JavaScript gets the current date() and converts it to mm / DD / yyyy, June 23, 2022
- Explanation of HTTP network protocol
- Vue3+vite3 to develop Netease cloud music Day1 backend environment
- You can't even tell how nginx forwarded the request to you. It's good to say that you're not a crud Engineer?
- Baidu map JavaScript API, the earth mode is always similar to the "night mode", solve!
- Vue- different interfaces after different roles log in
- Bugatti launched a two wheeled scooter with less than 1000 US dollars
- The publishing function written by Vue (the simple version of wechat applet cooperates with cloud data development), pictures can be submitted, words can only be printed, but not submitted (self-improvement submission)
- Front end export excel, JS xlsx export
- Wed, front-end Personal Learning Websites
- The project cannot run after webpack installation
- Webpack dev server cannot start normally cannot find module 'webpack / bin / config yargs‘
- Ajax request request plug-in on uniapp for its own use
- Determine whether a function exists in JavaScript - function_ exists
- [bug] @jsonformat has a problem that the date is less than one day when it is used
- Vue/js operation DOM full screen switch, full screen open dom requestFullscreen();
- [angular] angular removes the input spaces. The angular user-defined attribute instruction - prohibits the input box from entering spaces - and deletes the spaces in the copied content (with other solutions attached)
- Cruise is now charging for its driverless ride service in San Francisco
- Principles of vue3 compiler
- Reactiveeffect principle of vue3
- Patch update details for vue3
- Nexttick principle of vue3
- Pyqt5 how to make windows borderless and movable by dynamically loading the UI?
- How to open an account online for new bonds? Please bless me
- React usestate storage function
- CSS problem, card jitter
- () is a linear table that restricts the internal structure of data elements to only one character. A. Stack B. queue C. string D. array
- Reactnative 0.69 release
- The new design can be called a new generation. The gradient borderless grille has a high appearance value. The application drawing of Changan Ruicheng plus
- Render external link address URL video page via iframe - Vue
- Vue failed to parse source for import analysis because the content contains invalid JS syntax
- Differences between front-end set and map
- Difference between front-end foreach and map
- Front end array flattening
- How the front end judges the data type
- Front end CSS style expand and collapse
- Front end array de duplication
- Front end throttling and anti shake