current position:Home>Getting started with Vue
Getting started with Vue
2022-05-15 03:52:02【Li Changge s】
Vue: Fore and aft end separation
Build a progressive framework for the user interface , Layer by layer from bottom up
soc: The separation principle of attention
MVVM: Two way data binding
first Vue Program
The official tutorial Vue.js (vuejs.org)
Understood as a Keep listening to the page ajax
idea Need to install Vue.js plug-in unit
Vue On-line cdn
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
Put it in head Medium JS The code will be in Before the page is loaded Just read ,
And put it in body Medium JS Code , Will be in the whole After the page is loaded Read
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- View layer -->
<div id="vue">
{
{message}}
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script> <!-- ViewModel layer --> var vue = new Vue({
<!-- Between key values There must be spaces , It's like yml The grammar is the same --> <!-- binding id by vue The elements of --> el: "#vue", data: {
<!-- Model layer --> message: "Hello Vue!" } }) </script>
</body>
</html>
Basic grammar
Vue.js Template syntax | Novice tutorial (runoob.com)
All attributes are written , All of them are key-value Key value pair , use yml To understand vue
v-bind
Attribute binding vue Data command
v-bind:“message” amount to { {message}}
<div id="vue">
<span v-bind:title="message">
When the mouse hovers , You can see message Information about
</span>
</div>
Import links
<!DOCTYPE html><html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
Judge
<!-- No need to import links -->
<div id="vue">
<span v-if="message === 'A'">A</span>
<span v-else-if="message === 'B'">B</span>
<span v-else>C</span>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script> let vue = new Vue({
el: "#vue", data: {
message: "D" } }) </script>
loop
<div id="vue">
<!-- Comprehend C# Of foreach-->
<li v-for="(item,index) in items">
{
{item}}
</li>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script> let vue = new Vue({
el: "#vue", data: {
items: ["java", "html", "mysql", "redis"] } }) </script>
<!--index The subscript of the official default configuration -->
<li v-for="(item,index) in items">
{
{item}} -- {
{index}}
</li>
variant
<div id="vue">
<span v-for="item in items">
{
{item.message}}
</span>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script> let vue = new Vue({
el: "#vue", data: {
items: [ {
message: "java"}, {
message: "html"}, {
message: "mysql"}, {
message: "redis"} ] } }) </script>
<!-- Running results -->
java--0
html--1
mysql--2
redis--3
v-model Two way data binding
From the start ,vue.js The introduction of head in
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
vue Will ignore checked,select Value , Take only vue Of data The value in
<div id="vue">
<!-- Two way data binding : Assign the selected value to items-->
<select v-model="items">
<option disabled> Please select </option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<span> Selected {
{items}}</span>
</div>
<script> let vue = new Vue({
el: "#vue", data: {
items: "" } }) </script>
methods event
<div id="vue">
<!-- The binding event -->
<button value=" Click on me " v-on:click="test"></button>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script> let vue = new Vue({
el: "#vue", data: {
items: ["java", "html", "mysql", "redis"] }, methods: {
test: function (){
<!-- Value vue data Medium items--> for (let item in this.$data.items) {
alert(item) } }//test }//method }) </script>
computed Compute properties
computed Cache the result into a value
<div id="vue">
<!--computed It's a value -->
<span>computed:{
{getTime}}</span>
<span>methods:{
{getTime1()}}</span>
</div>
<script> let vue = new Vue({
el: "#vue", //computed Cache the result into a value , All can be methods replace computed: {
getTime() {
return " Time stamp " + Date.now(); } }, // When you have a duplicate name , Default call methods methods: {
getTime1: function () {
return Date.now(); } } }) </script>
On the console you can see ,computed Is to cache the value locally
vue.getTime
' Time stamp 1652064179289'
// Do not refresh page , Multiple runs , Results the same
vue.getTime
' Time stamp 1652064179289'
vue.getTime1()
1652064259827
//methods Will refresh the data
vue.getTime1()
1652064266181
Axios Asynchronous communication framework
On-line cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Vue - Life cycle explanation - Simple books (jianshu.com)
info In the format : Don't write , But don't make a mistake
<div id="vue">
<span> City :{
{info.address.city}}</span>
<a :href="info.url"> website </a>
</div>
<script> let vue = new Vue({
el: "#vue", // This function returns the name of the component instance data object data(){
return {
info: {
// The value can not be written , But the format must be the same url: null, address: {
city: null } } } }, //vue Data mount html After the template is completed , do ajax The hook function of , It's only going to be executed once mounted(){
//get example : use response.data Read the data in the file json data , Response to the info attribute axios.get("data/data.json").then(response=>(this.info = response.data)); } }) </script>
Solution to the problem of front-end page flickering
Vue.component Components
props Property names in cannot be capitalized
<div id="vue">
<!-- Use components child, to childItem Binding value item-->
<child v-for="item in items" v-bind:children="item"></child>
</div>
<script> // Component name , Component entity Vue.component("child",{
// The ginseng props: ['children'], // Templates /** * html Label and its contents They all end up in lowercase * however vue Case sensitive */ template: "<li>{
{children}}</li>" }) let vue = new Vue({
el: "#vue", data: {
items: ["java","mysql","html"] } }) </script>
slot
<div id="vue">
<child>
<slot1 slot="slot1" v-for="item in items" :item="item"></slot1>
<slot2 slot="slot2" v-for="(item,index) in items" :index="index"></slot2>
</child>
</div>
<script> Vue.component("child",{
template: "<li>\ <slot name='slot1'></slot>\ <slot name='slot2'></slot>\ </li>" }) // slot 1 receive item data Vue.component("slot1",{
props: ['item'], template: "<span> Elements :{
{item}}---</span>" }) // slot 2 receive index data Vue.component("slot2",{
props: ['index'], template: "<span> Indexes :{
{index}}</span>" }) let vue = new Vue({
el: "#vue", data: {
items: ["java","mysql","html"] } }) </script>
Event distribution
Realization function : There is a button in the slot , You can delete elements , But what is deleted is Vue Object elements in the instance
according to Two way binding principle , use Front end to mediate Vue Between instances and components Of Call each other
vue.js in this.$emit The understanding of the
<div id="vue">
<!-- The binding event , It's called Vue The method in the example -->
<!-- Click on button The event is executed when remove,remove There is this.$emit('test','index') -->
<father v-on:test="removeItem(index)">
<child slot="child" v-for="(item,index) in items" :index="index"></child>
</father>
</div>
<script> Vue.component("father",{
//@click: binding vue Click to listen template: "<div>\ <slot name='child'></slot>\ <button @click='remove'> Remove elements </button>\ </div>\ ", methods: {
remove: function (index){
/** hold remove The event will be distributed , Pass parameters index When remove Execution time , The child will tell the parent : Trigger custom event test, That is to say Vue In the instance removeItem event */ this.$emit("test",index); } } }) Vue.component("child",{
props: ['index'], template: "<span>{
{index}}</span>" }); let vue = new Vue({
el: "#vue", data: {
items: ["java","mysql","html"] }, methods: {
removeItem: function (index){
// from index Bit starts to delete , Delete one at a time // Can increase , Delete , Change this.$data.items.splice(index,1); } } }) </script>
splice Use https://blog.csdn.net/qq_44921114/article/details/108608851
Vue-cli( The scaffold )
node.js Comprehend maven
Use Customized by Ali cnpm Command line tools Instead of default npm, Enter the following code
After successful installation , How to install dependency package later and npm It's the same , It's just npm The order for is cnpm That's all right. .
npm install -g cnpm --registry=https://registry.npm.taobao.org
Check if the installation is successful :
$ cnpm -v
C:\Users\ Trees \AppData\Roaming\npm Package storage path
If something goes wrong ,node.js Will tell you how to solve , Just execute the code he told you
vue list Check the available packages
install vue-cli
npm ERR! enoent ENOENT: no such file or directory, open ‘D:\package.json‘
Webpack Static module packager
Asynchronous load module , Multiple modules can be loaded in parallel
Comprehend : hold es6 Standardized front-end projects , Pack it up es5 standard
VUE-CLI Webpack Install and use
first webpack Program
Create a new one Only .idea Empty project for
hello.js amount to java Custom class
// Expose one sayHi Methods to the outside world
exports.sayHi = function () {
// Then I'll write on the page
document.write("<h1>Hello webpack!</h1>");
}
main.js The main entry of the program
// Import... In the current directory hello.js
var hello = require("./hello");
hello.sayHi();
webpack.config.js: Master profile ,webpack4.0 The last file name should be webpack.config.js
// Export the module to
module.exports = {
// entrance : Where to read
entry: "./modules/main.js",
// Where to output
output: {
filename: "./js/bundle.js"
}
}
Console operation webpack pack , Then, an dist Catalog
The test page Introduce the generated js file , Is equivalent to introducing hello.js
<script src="dist/js/bundle.js"></script>
ERROR in Entry module not found: Error: Can’t resolve ‘./src’ in XXX A solution for
webpack --watch Thermal deployment
Vue-router
Comprehend **@RequestMapping**
VueRouter Routing installation uses
install vue-router, Save to dev In the environment , That is to say config Under the table of contents
cnpm install vue-router --save-dev
In a vue Under the project
Custom components
Content.vue
<template>
<h1>Hello Vue-Router!This is my first VueContent.</h1>
</template>
<script> // Export a component , named Content, It is also equivalent to naming the current component as Content export default {
name: "Content" } </script>
<!--scoped Indicates that it is only valid on the current page -->
<style scoped> </style>
Main.vue
<template>
<h1>Hello Vue-Router!</h1>
</template>
<script> export default {
name: "Main" } </script>
<style scoped> </style>
The official custom is to call all kinds of configuration files index.js
router In the catalog index.js
// Import files and modules ( from node_modules Import ), Random names
import Vue from "vue"
import VueRouter from "vue-router"
import Main from "../components/Main"
import Content from "../components/Content";
// above Vue Instance installation routing ( Add the plug-in )
Vue.use(VueRouter)
// Instantiate and export the route
export default new VueRouter({
routes: [
{
// After entering the path in the address bar , Will jump to Content Components
path: "/content",
name: "Content",
component: Content
},
{
path: "/main",
component: Main
}
]
})
main.js Vue Master profile for the project
// 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'
// Automatically scan the... In the directory index.js file
import router from './router/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
// Using routing , It is also equivalent to importing all routes
router,
components: {
App },
template: '<App/>'
})
App.vue The main interface of the project
<template>
<div id="app">
<!-- Must be wrapped with labels , Otherwise, the content will not be displayed -->
<!-- Jump -->
<router-link to="/main"> home page </router-link>
<router-link to="/content"> Content page </router-link>
<!-- Show the view -->
<router-view></router-view>
</div>
</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>
npm run dev Run the packaged project
VueRouter Report errors :Uncaught TypeError: Object(…) is not a function
Integrate ElementUI
// install element-ui
cnpm i element-ui -S
// Installation dependency
cnpm install
// install SASS loader ( strengthening CSS The auxiliary tools of , strengthening CSS function )
cnpm install sass-loader node-sass --save-dev
npm run dev
Go to element-ui Official website , Copy their code
ElementLogin.vue( Custom login component )
<template>
<div>
<el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
<h3 class="login-title"> Welcome to login </h3>
<el-form-item label=" account number " prop="username">
<el-input type="text" placeholder=" Please enter your account number " v-model="form.username"/>
</el-form-item>
<el-form-item label=" password " prop="password">
<el-input type="password" placeholder=" Please input a password " v-model="form.password"/>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="onSubmit('loginForm')"> Sign in </el-button>
</el-form-item>
</el-form>
<el-dialog title=" reminder " :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
<span> Please enter your account number and password </span>
<span slot="footer" class="dialog-footer">
<el-button type="primary" @click="dialogVisible = false"> indeed set </el-button>
</span>
</el-dialog>
</div>
</template>
<script> export default {
name: "Login", data() {
return {
form: {
username: '', password: '' }, // Form validation , Need to be in el-form-item Add... To the element prop attribute rules: {
username: [ {
required: true, message: ' Account number cannot be empty ', trigger: 'blur'} ], password: [ {
required: true, message: ' The password cannot be empty ', trigger: 'blur'} ] }, // Dialog shows and hides dialogVisible: false } }, methods: {
onSubmit(formName) {
// Bind validation to the form this.$refs[formName].validate((valid) => {
if (valid) {
// Use vue-router Route to the specified page , This is called programmed navigation this.$router.push("/main"); } else {
this.dialogVisible = true; return false; } }); } } } </script>
<style lang="scss" scoped> .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>
To configure router
// Import element-ui modular , and css file
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import ElementLogin from "../components/ElementLogin";
Vue.use(Element);
export default new VueRouter({
routes: [
{
path: "/login",
component: ElementLogin
}
]
})
main.js change App.vue The generation method of is adaptation Element
new Vue({
el: '#app',
router,
//ES6 Writing , Is to generate a called App The node of , Mount to the root node .
//https://www.jianshu.com/p/0ea899e233a9
render: h => h(App)
})
App.vue Use components
<template>
<div id="app">
<router-link to="/login"> Sign in </router-link>
<router-view></router-view>
</div>
</template>
Run Publishing npm run dev
Error reporting solution
Module build failed: TypeError: this.getOptions is not a function install node-Sass Report errors
Or the official will tell you which version to use Module build failed: Error: Node Sass version 7.0.1 is incompatible with ^4.0.0.
cnpm install [email protected] --save-dev
Automatically generate websites , file Documentation (docsify.js.org)
Route nesting
Is in the Put a component Put it in Under another component
index.js
export default new VueRouter({
routes: [
{
path: "/main",
component: Main,
// Route nesting , Last visit /login when , Must be in /main Next
children: [
{
path: "/login",
component: ElementLogin
}
]
}
})
main.vue
<template>
<!-- It must all be put in the label -->
<div>
<h1>Hello Vue-Router!</h1>
<router-link to="/login"> Sign in </router-link>
<router-view></router-view>
</div>
</template>
Parameter transfer and redirection
When the value is taken , All elements must be wrapped with labels
App.vue
<!-- Binding parameters 1 To named login Routing of -->
<router-link :to="{name:'login',params:{id:1}}"> Sign in </router-link>
route index.js
routes: [{
// When accessing the path, you must carry id Parameters of
path: "/login/:id",
name: "login",
component: ElementLogin
}
]
Receive parameters directly
<h1>{
{$route.params.id}}</h1>
props Father and son pass on Ginseng
index.js
name: "login",
// Allow parameters to be passed
// When props Set to true when ,route.params Will be set to the props.
props: true,
Use... In the page to be jumped props Receive the corresponding parameters , Can be used directly
<h1>{
{id}}</h1>
export default {
name: "Login",
props: ['id'],
push Pass form parameters
The login page carries the parameters in the page form in the export
export default {
name: "Login",
data() {
return {
form: {
username: '',
password: ''
},
// Form validation , Need to be in el-form-item Add... To the element prop attribute
rules: {
username: [
{
required: true, message: ' Account number cannot be empty ', trigger: 'blur'}
],
password: [
{
required: true, message: ' The password cannot be empty ', trigger: 'blur'}
]
},
// Dialog shows and hides
dialogVisible: false
}
},
methods: {
onSubmit(formName) {
// Bind validation to the form
this.$refs[formName].validate((valid) => {
if (valid) {
// Use vue-router Route to the specified page , This is called programmed navigation
// Carry parameters when reaching the specified page
this.$router.push("/main/"+this.form.username);
} else {
this.dialogVisible = true;
return false;
}
});
}
}
}
index.js Configure parameter list in routing
path: "/main/:name",
props: true,
component: Main
Use
<template>
<div>
<h1>{
{
name}}</h1>
</div>
</template>
<script>
export default {
name: "Main",
props: ['name']
}
</script>
Redirect
routes: [{
path: "/element",
component: ElementLogin
}, {
path: "/login",
name: "login",
props: true,
// Redirect
redirect: "/element"
}
]
Global routing and routing hooks
Global routing 404
// When at all path When none of them match , Jump
path: "/*",
component: Main
Routing mode
hash: Path belt # Symbol
history: The path does not take # Symbol
The routing index.js
export default new VueRouter({
mode: "history",
routes: [
Hook function and axios
vue-axios|axios Chinese net | axios (axios-js.com)
The test directory is generally called mock, Put it in static Under the table of contents
install axios modular :cnpm install axios,cnpm install vue-axios
Import axios modular
import Axios from "axios"
import VueAxios from "vue-axios"
// Must bind first VueAxios, Then the Axios
Vue.use(VueAxios,Axios)
export default {
name: "Main",
beforeRouteEnter: (to, from, next)=>{
console.log(" Before entering the route ");
//vm Implementation calls methods Release after the method in
next(vm => {
vm.getData();
});
},
beforeRouteLeave: (to, from, next)=>{
console.log(" After entering the route ");
next();
},
methods: {
getData: function (){
//get Mode request file
this.axios({
method: "get",
url: "../../../static/mock/data.json"
}).then(function (response){
// The requested data will be encapsulated in response in
console.log(response);
})
}
}
}
copyright notice
author[Li Changge s],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/131/202205111509391022.html
The sidebar is recommended
- Build an electron project based on Vue from scratch
- In Vue project, solve the problem of verification conflict when eslint and prettier are used at the same time
- Vue3 + vuecli4 solve chunk vendors JS file is too large. Scheme summary
- Scheme summary of eslint check before vue3 + vite configuration project operation and eslint check before git submission
- Fatal authentication failed for 'httpxxxx Git 'solution
- Vue's solution to the compatibility of hevc encoded video in each end browser
- Record the solution to the error in obtaining the picture in springboot in Vue
- [Vue] detailed analysis of the life cycle function of Vue components
- [Vue] deeper understanding of user-defined attribute props
- [Vue] front end error: cannot read properties of undefined (reading 'split')
guess what you like
[Vue] asynchronous problem of component value transfer -- the sub component gets the data slowly
[Vue] Vue data changes, but the page is not updated in real time
[element UI] use of form verification -- detailed explanation
[Vue] use of slots - Review
The influence on the fixed positioning element of the inner layer when the outer element has a fixed height and overflows and rolls
Precautions
Change detection strategy of angular component
Angular service and @ injectable
JS, HTML and CSS are not compatible and do not use common knowledge
Properties to be known in angular @ component
Random recommended
- Angular acquisition and operation DOM
- Html2canvas problem
- Use day in Vue JS (time and date processing library)
- Vue cli configuring preprocessor global variables (take less as an example)
- How to use H5 custom tags in Vue?
- Come on, vue2 customize global loading
- Come on, Vue move the end suspension ball assembly
- React routing foundation and transmission parameters
- Come on, Vue graphic verification code component
- JavaScript judges browser types and kernels at home and abroad (including 360, QQ, Sogou, etc.)
- ArcGIS JavaScript 4. Generates a rectangular buffer at the point of X
- Node under window JS installation, environment configuration, setting Taobao image
- Understanding of prototype and prototype object of JavaScript
- How to customize the startup port of react project!
- Why vue3 0 using proxy to realize data listening 2021-06-21
- Front end artifact - download, configuration and use process of Charles (vase) [Mac version]
- React next configures SVG loader and supports SVG configurability
- React native Android phone cannot be opened after installation. Flash back!
- Fetch and Axios failed to request on Android, with error messages: network request failed and network error
- How to upgrade react Babel 7.1.0
- babel7. 0 compatible with IE browser
- Nginx configuring reactrouter browserhistory browserrouter
- JS, react use html2canvas page screenshot and export
- Big data front-end visualization screen -- the road of front-end development
- [a quick introduction and comparison of multiple languages -- JavaScript, typescript, python, golang, trust, Java, ruby]
- Vue element admin login function, token filling, language conversion, routing setting
- Summation of corresponding position elements of multiple lists in Python
- Discussion on HTML page knowledge
- Using Ajax to realize non refresh paging
- HTTP format
- Zhang San has a meal - did he eat the difference between get and post in HTTP?
- The ultimate actual combat of the most complete tourism project based on spring boot + Vue front-end and back-end separation in history (with source code attached), none of them!!!
- Vue basic grammar
- LeetCode 217. There are duplicate elements
- Pagoda does not configure the solution of SSL site accessing HTTPS and jumping to other websites
- Vue3 isProxy
- About the problem that the container will hang up after starting nginx in the docker container
- Introduction to JavaScript
- The core element of large-scale software design is to control complexity. What is the root cause?
- What are the core elements of large-scale software design?