A, do not write son father what is the problem
<div id='app'>
<! -- num -->
<p>{{num}}</p>
<comp :num='num'></comp>
</div>
<template id="tmp">
<div>
<h1>{{num}}</h1>
<button @click='add'>button</button>
</div>
</template>
<script>
let comp = {
template: '#tmp'.props: ['num'].methods: {
add() {
this.num += 10}}},new Vue({
el: '#app'.data: {
num: 10
},
components: {
comp
}
})
</script>
Copy the code
When you click the button, it adds only the child’s num, and does not change the parent’s num.
I don’t see any effect right now. Here’s an example:
<div id='app'>
<! -- num -->
<p>{{num[1]}}</p>
<comp :num='num'></comp>
</div>
<template id="tmp">
<div>
<h1>Num: {{num[1]}}</h1>
<button @click='add'>button</button>
</div>
</template>
<script>
let comp = {
template: '#tmp'.props: ['num'].methods: {
add() {
console.log(this.num);
this.num[1] + =10}}},new Vue({
el: '#app'.data: {
num: [10.20.30]},components: {
comp
}
})
</script>
Copy the code
When the data is in the form of an array, if you modify it, the page will not process it, but the data will still change
Note: Under normal circumstances, do not change the data only in the child element, which is easy to make the data inconsistent and difficult to maintain the code later. Therefore, when making changes related to parent component data in the child component, you must first define the code to be modified in the parent component, and then pass it to the child component in the form of custom events for data modification, so as to unify the data in the whole file.
Second, the Webpack
Essentially, WebPack is a static module packaging tool.
In order for our modular code to be compatible across a wide variety of browsers, we have to use other tools; One of the core aspects of WebPack is that it allows modular development and helps us deal with dependencies between modules. Not only Javascript files, our CSS, images, JSON files, etc. can be used as modules in WebPack, which is the modular concept of WebPack.
2.1. Gulp and Webpack
Gulp focuses on the control and management of the whole process of front-end development (like pipelinization). We can configure different tasks for Gulp (through Gulp’s gulp.task() method, Such as starting server, sASS /less precompilation, file consolidation and compression, etc.) to allow gulP to implement different functions to build the whole front-end development process.
gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify'); // Compress the code
Js / / compression
gulp.task('uglify'.function(){
var combined = combiner.obj([
gulp.src('src/scripts/**/*.js'), // The path of the js file to compress
sourcemaps.init(),
uglify(), Js / / compression
sourcemaps.write('/'),
gulp.dest('dest/scripts') // The directory of the generated js files
]);
});
// Default task
gulp.task('default'['uglify']);
Copy the code
Webpack is also known as module packing machine, which can also be seen that Webpack focuses more on module packaging, of course, we can put all resources in the development (pictures, JS files, CSS files, etc.) can be regarded as modules, originally Webpack itself is designed for front-end JS code packaging, It was later extended to package other resources. Webpack handles resources through loaders and plugins.
2.2 Initial experience of Webpack
1. Generate project dependency files
// Generate package.json file after execution
npm init -y
Copy the code
2. Install dependencies
// The last parameter -d is installed in the devDependencies object of package.json, and can also be replaced with --save-dev
npm install webpack@4.441. webpack-cli@3.312. -D
// Install webpack globally and webpack-cli
npm i webpack@4.441. webpack-cli@3.312. -g
// -s is short for "save". Add it to the dependencies object and replace it with "save"
npm install jquery -S
Copy the code
// package.json
{
"name": "webpack-demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": ""."license": "ISC"."devDependencies": {
"webpack": "^ 4.40.2"."webpack-cli": "^ 3.3.9"
},
"dependencies": {
"jquery": "^ 3.4.1 track"}}Copy the code
DevDependencies and dependencies:
When the NPM package is published, the module under its dependencies is downloaded as a dependency. The module below devDependencies does not download automatically; For projects, however, NPM install automatically downloads devDependencies and the module below them.
3. Create an entry file
index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script src="./index.js"></script>
</html>
Copy the code
index.js
import $ from 'jquery'
$('ul li:even').css({background: 'red'$(})'ul li:odd').css({background: 'green'})
Copy the code
Open it in the browser
4. Pack using webPack
// Run the output command
webpack index.js -o dist/bundle.js
Copy the code
This error occurs because the command line will look for the global Webpack, but we do not have the global webpack installed, so we can install the global Webpack, or use a script to start
package.json
{
"name": "webpack-demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
"start": "webpack index.js -o dist/bundle.js"
},
"author": ""."license": "ISC"."devDependencies": {
"webpack": "^ 4.40.2"."webpack-cli": "^ 3.3.9"
},
"dependencies": {
"jquery": "^ 3.4.1 track"}}Copy the code
Execute the start command added in the package.json file
// Generate the dist folder and bundle.js file
npm run start
Copy the code
Then change the place where index.html was introduced into index.js to bundle.js generated by WebPack
<! -- index. The HTML file - >
<! --<script src="./index.js"></script>-->
<script src="./dist/bundle.js"></script>
Copy the code
To optimize the
The webpack index.js -o dist/bundle.js sentence can be written in a configuration file
Webpack. Config. Js:
const path = require('path');
module.exports = {
entry: path.join(__dirname, './index.js'), // dirname indicates the index to the directory where the file resides
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js'}}Copy the code
Package. Json:
"scripts": {
"start": "webpack --config webpack.config.js"
}
Copy the code
5.webpack-dev-server
If you change the background color of index.html from red to gray, you will find that the browser refresh does not work, so you need to run the NPM run start command again. In this case, you need to use webpack-dev-server.
Installation:
npm install webpack-dev-server -D
Copy the code
Package. Json:
"scripts": {
"start": "webpack-dev-server --config webpack.config.js --open --port 3002 --hot"
}
// --open Automatically opens the browser
// --port is listening on port 3002
// --hot automatically updates
Copy the code
Note here:
1, after starting webpack-dev-server, you will not see the compiled files in the target folder, the real-time compiled files are saved in memory. To see the bundle.js file, run localhost:3002/bundle.js
Since bundle.js is no longer in the dist directory, if there are no other webpack configuration items, the command above could also be shortened to:
"scripts": { "start": "webpack-dev-server --open --port 3002 --hot" } Copy the code
index.html
<script src="./bundle.js"></script>
Copy the code
6. html-webpack-plugin
NPM install -d [email protected]
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.join(__dirname, './index.js'),
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, './index.html'),
filename: 'index.html'}})]Copy the code
Delete the bundle.js reference from the index.html file, because the html-webpack-plugin automatically adds the bundle to our index.html code
7. css-loader
Create an index. CSS
index.css
body {
background: skyblue;
}
Copy the code
index.js
import $ from 'jquery'
$('ul li:even').css({background: 'gray'$(})'ul li:odd').css({background: 'green'})
import './index.css'
Copy the code
Webpack does not recognize the. CSS file by default, so we need to interpret the. CSS file into the correct module by loader.
Install CSS-loader and style-loader
npm install css-loader style-loader -D
//index.css -> bundle.js -> style-loader -> <style> index.html
// css-loader is used to parse the index.css file into a module that webPack can recognize and then package it into bundle.js, but this style is not displayed successfully in the browser.
// Style-loader is used to bind styles packaged in bundle.js to the browser and display them as style tags
Copy the code
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.join(__dirname, './index.js'),
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, './index.html'),
filename: 'index.html'})].module: {
rules: [{
test: /\.css$/,
use: ['style-loader'.'css-loader'] // Note that the array is read in reverse (i.e. from right to left)}}}]Copy the code
Add: The imported file is less
NPM install less-loader less-d
Rules:
{
test: /.less$/,
use: [‘style-loader’, ‘css-loader’, ‘less-loader’]
}
8. Turn ES5 ES6
The installation
npm install babel-core babel-loader@7.1. 5 babel-plugin-transform-runtime babel-preset-env babel-preset-stage-0 -D
Copy the code
const fn = () = > {
console.log(123)}Copy the code
Configure the loader
{test:/\.js/,use:['babel-loader'].exclude:/node_modules/}
Copy the code
Exclude excludes node_modules download dependencies. This speeds up site development and we only need to SRC our project
Compile the source file.
Add. Babelrc file
{
"presets": ["env"."stage-0"]."plugins": ["transform-runtime"]}Copy the code
Add and introduce main.js to index.js, then use es6 syntax
const fn = () = > {
console.log(123)
}
fn()
Copy the code
Execute command compilation
npm run start
Copy the code
The compiled result
var fn = function fn() {\n console.log(123); \n}Copy the code
This is the basic configuration for WebPack.
explain
Babel-present-env includes only babel-present-2015, 2016, 2017, not babel-stage-x, nor babel-polyfill
Babel-present-env only converts new syntax such as arrow functions, not new API such as array. include
API and smoothing out differences between browsers (compatible with IE) requires Babel-Polyfill
Babel-polyfill is polluting and violent. Where is babel-plugin-transfrom-runtime needed
Where to convert.
The babel-plugin-transform-Runtime does three things:
When you use generators/async functions, automatically introduce babel-Runtime /regenerator (using regenerator)
Does not pollute the current environment.
Automatically introduces babel-Runtime /core-js and maps ES6 static methods and built-in plugins (polyfill without global contamination,
However, instance methods such as “foobar”. Includes (” foo “) cannot be used properly.
Remove inline Babel helpers and replace them with the babel-Runtime /helpers module
Code).
9. HTML hot update
After installing the HTML-webpack-plugin, install:
npm install --save-dev raw-loader
Copy the code
Configure raw-loader in webpack.config.js:
module.exports = {
......
module: {
rules: [{test: /\.(htm|html)$/,
use: [
'raw-loader']},... ] }}Copy the code
Add HTML to index.js:
import './index.html'
Copy the code
Vue CLI preparation
The Node version
Vue CLI requires Node.js version 8.9 or later (12.11.0 is recommended). You can use NVM or NVM-Window to manage the Node version on your computer.
Vue CLI scaffolding installation package:
npm install -g @vue/cli
# OR
yarn global add @vue/cli
Copy the code
Once installed, you can access vue commands from the command line. You can verify that vue is installed successfully by simply running it and seeing if it displays a help list of all available commands.
You can also use this command to check if the version is correct (4.x) :
vue --version
Copy the code
If the installation is slow, you can switch the download source to taobao’s source:
NPM corresponding Taobao download source Settings:
Switch / / taobao mirror image source NPM config set registry/https://registry.npm.taobao.org/ / view the download source NPM config get registryCopy the code
Yarn corresponding Taobao download source Settings:
Switch / / taobao mirror image source yarn config set registry/https://registry.npm.taobao.org/ / view the download source yarn config get registryCopy the code
Create a project
Initialize the project
vue create
Run the following command to create a new project:
vue create hello-world
Copy the code
You will be prompted to choose a preset. You can choose preset, which includes the basic Babel + ESLint setting, or choose “Manually selected Features” to recall the desired feature.
This default setting is great for quickly prototyping a new project, while manual Settings provide more options that are more desirable for production-oriented projects.
Here is a brief description of each function:
- TypeScript supports source writing in TypeScript.
- Progressive Web App (PWA) Support PWA Support
- The Router routing
- Vuex status management
- CSS pre-processors CSS pre-processors are supported.
- Linter/Formatter supports code style checking and formatting.
- Unit Testing supports Unit Testing.
- E2E Testing Supports E2E Testing.
If you decide to manually select a feature, you can choose to save the preset option as a future reusable preset at the end of the action prompt
~/.vuerc
The saved preset file will be stored in a JSON file named.vuerc in the user’s home directory. Edit this file if you want to change preset/option that is saved.
During project creation, you will also be prompted to choose your preferred package manager or use the Taobao NPM image source to install dependencies faster. These selections will also be stored in ~/.vuerc.
The project structure
Project directory
node_modules
public // Static resource file
|-favicon.ico
|-index.html
src // Project source code, where the code is written
|-assets
|-App.vue
|-main.js
.browserslistrc // Browser support
.eslintrc.js // Code related support
.gitignore Git ignores files
babel.config.js // Babel configures ES syntax conversion
package-lock.json // NPM installs dependent library details
package.json // NPM depends on library version information
postcss.config.js // CSS-related transformations
README.md // Project description
vue.config.js // Vue and Webpack configuration items
Copy the code
vue.config.js
Vue. Config. js is an optional configuration file that is automatically loaded by @vue/cli-service if it exists in the root directory of the project (the same as package.json). You can also use the vue field in package.json, but note that this requires you to follow the JSON format strictly.
This file should export an object containing options:
// vue.config.js
module.exports = {
/ / options... (e.g. :)
lintOnSave: false / / close eslint
}
Copy the code