Step 1: Install Node.js

Node.js installation step-by-step tutorial

Step 2: Install vuE-CLI globally

npm install @vue/cli -g

Step 3: Create a new project based on the WebPack template

(1) Download webpack offline template

Download: github.com/vuejs-templ…

Once you’ve downloaded it, unzip it to your local user directory.vue-templatesdirectory

(2) Create a project

Go into your project directory and create a new project based on the WebPack template. Let’s say you want to create a project called vue_demo in the Web folder on drive E. Can be based on the following process:

1. The keyboardwin+RThe inputcmdPress Enter. 2. Run the commande:Press Enter to go to drive E. 3. Run the commandCD webPress Enter to go to the Web folder. 4. Run the commandvue init webpack vue_demo --offlineenter

Press Enter to enter the configuration for some projects. For starters using Vue, most of the configuration will work as default, but for beginners Use ESLint to Lint your code? It is best to select No for this configuration, because if you select Yes, it will impose a strict pattern on the specification of your code (i.e. there will be many errors, such as two Spaces before a line of code).

Once created, we follow its instructions and enter these two commands: 1. Type CD vue_demo and press enter to go to the project directory 2. Type NPM run dev and press Enter to run the project

The project starts compiling, and when it is finished, the following command window appears

We copy the URL that it gave us into the browser

Step 4: Directory structure analysis

At this point the project is created, and then I pull the project folder into the compiler, VS or WebStrom or HbuildX, I pull into HX for personal preference.

Open the project folder and look inside the file directory structure as follows

Vue_demo: project folder, which contain code across the entire project | build: webpack related configuration folder (basic does not need to be modified) | - dev - server. Js: through express start | - backend server config: Webpack related configuration folder (basic does not need to be modified) | -- index. Js: the specified port number, and a static background resources folder | - node_modules: depend on the folder | - SRC: source folder | - assets: Static resources, such as CSS, js, pictures | - components: vue component and its related resources folder | - the router: routing file | -- App. Vue: application of main component | -- main. Js: js | - application entrystatic: static resource folder, some common things. | - babelrc: Babel's configuration file. | - eslintignore: eslint check ignore configuration. | - eslintrc. Js: Eslint check the configuration of the | -. Gitignore: the git version control ignore configuration | -- index. HTML: main page file | -- package. Json: application package configuration file | -- README. Md: Readme file for application descriptionCopy the code

index.html

<! DOCTYPEhtml>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>vue_demo</title>
  </head>
  <body>
    <div id="app"></div>
    <! -- built files will be auto injected -->
  </body>
</html>
Copy the code

Index.html typically defines only an empty root node, under which instances defined in main.js are mounted and populated by vue components.

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'	// The Vue is uppercase and the Vue is lowercase
import App from './App'	// Import the component App
import router from './router' // Import routes

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app'.// Mount the root node corresponding to div id="app" in index.html
  router,
  components: { App },// Import components
  template: '<App/>'// The mapping component is a label
})

Copy the code

Main.js mainly introduces the VUE framework, root components and routing Settings, and defines vue instances.

App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <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>
Copy the code

A VUE page is usually composed of three parts: template, JS (Script) and style.

  1. template

A template can contain only one parent node.
is short for
, which is a child routing view. The following routing pages are displayed here.

  1. script

A VUE is usually written using ES6 syntax and exported using Export Default. It can contain data, life cycles (Mounted), methods, and so on.

  1. style

The instance

Run the project as shown below

The problem with this is that every time we compile, we have to manually copy the URL to the browser and open it again, which is a little bit of a hassle. We can change the autoOpenBrowser parameter in the index.js file in the config folder to true to make the browser open automatically after each compilation.

Demand analysis

Do a message board function, including message function and display message function

Building static pages

Build static pages using the BootStrap library

<! DOCTYPEhtml>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Message board</title>
    <link rel="stylesheet" type="text/css" href=".. /.. / the bootstrap - 5.0.0 - dist/CSS/bootstrap CSS" />
    <link rel="stylesheet" type="text/css" href="./Comment.css"/>
  </head>

  <body>
    <div class="container-fluid">
      <! -- Page header title bar -->
      <div class="row clearfix comment-header">
        <div class="col-md-12 column">
          <div class="card text-center">
            <div class="card-body">
              <h1 class="card-title comment-title">Vue message board</h1>
            </div>
          </div>
        </div>
      </div>
      <! Page content, including message filling area and message viewing area -->
      <div class="row clearfix">
        <! -- Message filling area -->
        <div class="col-md-4 column">
          <div class="card">
            <h5 class="card-header">Please fill in your message.</h5>
            <div class="card-body">
              <div class="mb-3">
                <textarea class="form-control" rows="3"></textarea>
              </div>
              <button type="button" class="btn btn-primary">Submit a message</button>
            </div>
          </div>
        </div>
        <! -- Message viewing area -->
        <div class="col-md-8 column">
          <div class="card comment-card">
            <h5 class="card-header">Messages are 1</h5>
            <div class="card-body">
              <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
              <a href="#" class="btn btn-primary">delete</a>
            </div>
          </div>
          <div class="card comment-card">
            <h5 class="card-header">Message 2 people</h5>
            <div class="card-body">
              <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
              <a href="#" class="btn btn-primary">delete</a>
            </div>
          </div>
          <div class="card comment-card">
            <h5 class="card-header">Messages are 3</h5>
            <div class="card-body">
              <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
              <a href="#" class="btn btn-primary">delete</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>

</html>
Copy the code

Analyze the page and extract components

Analyzing the static page above, you can see that three components can be extracted from the entire page

Extract components in code

So let’s create three new. Vue files under the components folder in the SRC folder and name them Add,List, and Item.

Component writing

Start by importing the Bootstrap library in index.html.

App.vue

<template>
  <div class="container-fluid">
    <! -- Page header title bar -->
    <div class="row clearfix comment-header">
      <div class="col-md-12 column">
        <div class="card text-center">
          <div class="card-body">
            <h1 class="card-title comment-title">Vue message board</h1>
          </div>
        </div>
      </div>
    </div>
    <! Page content, including message filling area and message viewing area -->
    <div class="row clearfix">
      <! -- Message filling area -->
      <Add :addComment="addComment"/>
      <! -- Message viewing area -->
      <List :comments="Comments" :deleteComment="deleteComment"/>
    </div>
  </div>
</template>

<script>
  import Add from './components/Add'
  import List from './components/List'

  export default {// The method to update the data is written in the component where the data resides
    data(){
      return {
        // Pass the Comment array to the List component via intercomponent communication
        Comments:[
          {
            username:'AAA'.contents:'Hello'
          },
          {
            username:'BBB'.contents:'Hahahaha'
          },
          {
            username:'CCC'.contents:'You're so moist.'}}},],methods: {addComment(comment){
        this.Comments.unshift(comment);
      },
      // Delete comments with the specified subscript
      deleteComment(index){
        this.Comments.splice(index,1); }},components: {
      Add,
      List
    }
  }
</script>

<style>
body {
  margin: 10px;
}

.comment-header {
  margin-bottom: 10px;
}

.comment-title {
  font-size: 5rem;
}

.comment-card {
  margin: 5px 0;
}

.card-body a.button {
  float: right;
}
</style>
Copy the code

Instead of looking at the rest of the code, just look at the markup, where we introduce two components: Add and List. The Add component then has a property addComment, whose value addComment is a method defined in methods in app. vue, which actually passes the parent component’s method to the child component so that the child component can call it. Similarly, the parent component passes a Comment array and a deleteComment method to the List.

Then look at the script tag section of app. vue

import Add from './components/Add'
import List from './components/List'
Copy the code

The two lines above are the import component

export defaultcomponents: {
      Add,
      List
    }
  }
Copy the code

The above code maps the imported components to tags, so we can use the
and tags in
.

Add.vue

<template>
  <div class="col-md-4 column">
    <div class="card">
      <h5 class="card-header">Fill in the message</h5>
      <div class="card-body">
        <div class="mb-3">
          <label for="username" class="form-label">The user name</label>
          <input type="email" class="form-control" id="username" placeholder="Please enter user name" v-model="username">
        </div>
        <div class="mb-3">
          <label for="Contents" class="form-label">Message content</label>
          <textarea class="form-control" id="Contents" rows="3" placeholder="Please enter message content" v-model="contents"></textarea>
        </div>
        <button type="button" class="btn btn-primary" @click="submitComment">Submit a message</button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      addComment: {
        type:Function.required:true}},data() {
      return {
        username: ' './ / user name
        contents: ' '.// Message content}},methods: {
      submitComment() {
        // 1. Check whether the data is valid
        const username = this.username.trim(); // Get username from data (trim trim)
        const contents = this.contents.trim();
        if(! username || ! contents) { alert("The entered user name or message content cannot be empty.");
          return;
        }
        // 2. Encapsulate the data as Comment objects
        const Comment = {
          username, //ES6's compact syntax
          contents,
        }
        // Add to app.vue's Comments array
        this.addComment(Comment);
        // 4. Clear the input
        this.username = "";
        this.contents = ""; }}}</script>

<style>

</style>
Copy the code

Prop is a set of custom attributes that you can register on components. When a value is passed to a prop attribute, it becomes a property of that component instance. By default, a component can have any number of props, and any value can be passed to any prop. Access this value in the component instance just as you would access the value in data.

props: {
      addComment: {
        type:Function.required:true}},Copy the code

So what this code means is that you register a custom addComment attribute for the Add component, and the value it receives is of type Function, and the attribute is mandatory.

Look at the code of add. vue again, you can see the execution process of this component is that the user enters the username and message content, v-model automatically collects the data into username and contents in data, and then clicks the submit message button. The component will execute the event submitComment of methods, and then submitComment will first determine whether the values of username and contents are valid, and then call the method passed in by the parent component through this.addComment. This method adds the comment parameter to the Comments array in the parent component. Finally, empty the values of username and Contens.

List.vue

<template>
  <div class="col-md-8 column">
    <item v-for="(comment, index) in comments" :key="index" :comment="comment"
          :deleteComment="deleteComment" :index="index"/>
  </div>
</template>

<script>
  import item from './Item.vue'
  export default {
    // Declare a receive property: this property becomes a property of the component object
    props: ['comments'.'deleteComment'].// Only the attribute name is specified
    components:{
      item
    }
  }
</script>

<style>

</style>
Copy the code

The List component is relatively simple. It contains a subcomponent Item, so the first step is to import the Item component into the List component, and then map the imported Item component to a label using the components parameter. Then the List component Props has two Props, Comments and deleteComment, where comments is used for a V-for loop and holds the content of all the comments to be displayed. DeleteComment is a method of passing a List to an Item as an intermediate component; the List itself does not use this method. Thus, communication between components is passed layer by layer.

Item.vue

/ / the root component<template>
  <div class="card comment-card">
    <h5 class="card-header">{{comment.username}}</h5>
    <div class="card-body">
      <p class="card-text">{{comment.contents}}</p>
      <a href="#" class="btn btn-primary" @click="deleteItem">delete</a>
    </div>
  </div>
</template>

<script>
  export default {
    props: {// Specifies the attribute name and the type of the attribute value
      comment:Object.deleteComment:Function.index:Number
    },
    methods: {deleteItem(){
        const {comment,index,deleteComment} = this;
        if(window.confirm('Delete or not${comment.username}Leave a message? `)){ deleteComment(index); }}}}</script>

<style>

</style>
Copy the code

The Item component has three Props, namely comment, deleteComment, and index. Comment and index are the data passed to it by its parent component, comment is an element in the Comments array of App component data, and index is the subscript of this element in the array. DeleteComment is a method passed from App to Item from List to remove elements from an array.

So the execution of the Item component is that when the delete button is clicked, the component’s deleteItem method will be executed, and the parent component’s deleteComment method will be obtained through the object deconstruction copy of ES6, and then executed. We can remove the index element from the Comments array in the App component.