Location>code7788 >text

vue2-scaffolding

Popularity:730 ℃/2024-11-21 14:15:30

Vue Scaffolding is the official standardized development tool (development platform) for Vue.

/zh/

Use of scaffolding

  1. Installation of scaffolding

    npm install -g @vue/cli
    
  2. Creating a project using scaffolding

    vue create vue-demo
    
  3. Enter the catalog to start the service

    npm run serve
    

scaffolding

node_modules
├── public
│ ├── : tab icon
│ └── : main page
├── src
│ ├── assets: store static resources
│ │ └──
│ │── component: Stores components.
│ └──
│ │── : summarize all components
│ │── : Entry file
├── .gitignore: Configurations ignored by git version control
├── : babel's configuration file
├── : application package configuration file
├── : application description file
├── : package version control file
├── : scaffolding configuration file
// Default
// Entry file for the entire project

// Importing vue
import Vue from 'vue'
// Import the App component, the parent of all components.
import App from '. /'

// Turn off production hints for vue
 = false

// Create the vue instance object vm
new Vue({
  // Place the App component into the container
  render: h => h(App),
}). $mount('#app') // mount the app container

<!-- default (setting)indexfile-->

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <!-- be directed againstieBrowser Configuration,have sb do sthieBrowsers render pages at the highest level-->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Open the ideal viewport for mobile-->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- Configure tab icons -->
    <link rel="icon" href="<%= BASE_URL %>">
    <!-- Configuring Page Titles-->
    <title><%= %></title>
</head>
<body>
<!-- Browser not supportedjs when, noscriptThe elements in the-->
<noscript>
    <strong>We're sorry but <%= %> doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong>
</noscript>
<!-- containers-->
<div ></div>
<!-- built files will be auto injected -->
</body>
</html>

render function

In the document.import Vue from 'vue’The imported vue is not complete and lacks a template parser, so you can't use the template attribute to set component tags.When we package the code, we don't need to parse the templates, so the template parser in the core code of vue doesn't work, so vue removes the template parser in order to minimize the size of the code, but we need to use it when we develop, so we create a render method to parse templates. In short, the goal is to keep the size of the packaged code as small as possible and improve performance.

About the different versions of Vue:

  1. Difference with:
    (1). Is the full version of Vue, including: core functionality + template parser.
    (2). It's the runtime version of Vue, which contains only: core functionality; no template parser.

  2. Because there is no template parser, you cannot use the template configuration item

    You need to use the createElement function received by the render function to specify the content.

renderfunction is mainly used to create virtual DOM nodes (VNodes). It is a JavaScript function that receives a function namedcreateElement(often abbreviated ash) function as an argument. ThiscreateElementfunction is used to build the VNode

    render(createElement){
        // Create a node <h1>hello world</h1> and rendered on the page
        return createElement("h1","hello world")

    }
// Pass in the App component, handing the template template from the app to render
// Shortened arrow function
render: h => h(App),

Scaffolding Default Configuration

Scaffolding hides the webpack configuration by default, use the following command to output the configuration as a js file for viewing (view only)

vue inspect > 

By default, the index, favicon, and src in the public folder are not allowed to be modified, and vue defaults to looking for the corresponding file from that path.

Modifiable configurationsThe scaffolding rules can be modified and personalized.

ref attribute

is used to register reference information (an alternative to id) to an element or subcomponent

The application gets the real DOM element on the html tag, the component instance object (vc) on the component tag

<template>
  <div >

    <! -- Set the title DOM ref to title -- >
    <h1 ref="title"> title </h1>
    <button @click="showDOm"> Click to get the DOM element of the title</button>
    <! -- Setting the component ref to be studen -- >

    <StudentComp ref="student"> </StudentComp>
  </div>
</template>

<script>.
import StudentComp from ". /components/";

export default {
  name: 'App', components: {
  components: {
    StudentComp
  }, data() { studentComp
  data() {
    return {name: "app->vue", address: "Beijing"}
  },
  methods: {
    showDOm() {
      // This is vc

      // In the template tag ref="title", the structure on top of vc is that there is a title key in vc's $refs object, and the value is the corresponding DOM.
      (this.$)
      // Use a ref on top of the component tag to get an instance of the component.
      (this.$)
    }
  }
}
</script>

props configuration

Allows the component to receive data from external sources and pass parameters dynamically.

  1. Accepts only parameters

    <script>
     export default {
      name: "StudentComp", data: function (
      data: function () {
        return { name: "vue", address: "Beijing"}
      }, // Arrays - <.
       // Array form -> use the props option to configure the city and age parameters
      props:["city", "age",]
    
    }
    
    
    </script>
    
    <template>
      <div class="student"> <h1>name:{{ name }}<
        <h1>name:{{ name }}</h1> </h1>
        <h1>address:{{ address }}</h1>
        {{city }}
        <! -- Add 1 after accepting age, age is a string by default, so it won't be calculated properly, only string splicing -->
        {{age + 1}}
    
      </div>
    </template>
    
     <! -- Pass in the corresponding data when using the component tag -->
    <StudentComp city="beijing" age="18"> </StudentComp>
    <! -- If you're passing in an expression, use the data binding syntax :age="xxxxx" -->
    
  2. Receive parameter-restriction type

    <script>
    export default {
      name: "StudentComp", data: function (
      data: function () {
        return { name: "vue", address: "Beijing"}
      }, // The object form.
    // Object form
      props: {
        city: String, // define the city parameter, String type
        age: Number // Define the age parameter, as a Number.
      }
    }
    
    
    </script>
    
    <template>
      <div class="student"> <h1>name:{{ name }}<
        <h1>name:{{ name }}</h1> </h1>
        <h1>address:{{ address }}</h1>
        {{ city }}
        <! -- The age restriction is of type Number and can be calculated normally -- >
        {{ age + 1 }}
    
      </div>
    </template>
    
  3. Receive Parameters-Type Restriction-Required Restriction-Default Value Setting

    // Nested objects
    props:{
        city:{
          type:String, // String type
          required:true // Required, defaults to false if not passed.
        },
        age:{
          type:Number,// number
          required: false,// Not required.
          default:18 // Default value, if not passed, go default
        }
      }
    
  4. props is read-only

    The props are read-only, what is passed in the template tag is what, Vue underlying will monitor your changes to the props, if changes are made, a warning will be issued, if the business needs really need to be changed, then please copy the contents of the props to a copy of the data, and then go to modify the data in the data

    // props has a higher rendering priority than data.
    // The page is rendered using myCity, which is initially the city of the props, passed in from the template tag.
    // Changing myCity changes the page's effect
    data: function () {
        return {name: "vue", address: "Beijing",myCity:}
      }
    
  5. Passing data through props

<template>
  <div>

    <Student :demo="demo"></Student>
  </div>
</template>

<script>


import Student from "@/components/";

export default {
  name: 'App',
  components: {
    Student
  },
  methods: {
    demo(name) {
      ("subassemblydata name", name)
    }
  }
}
<script>
 export default {
   // eslint-disable-next-line vue/multi-word-component-names
   name: "Student",
   // definepropscausality
   props:["demo"],
  data: function () {
    return {name: "vue", address: "Beijing"}
  },
  methods: {
    sendStudentName(){
      ()
    }
  }
}


</script>

mixin

Configurations shared by multiple components can be extracted into a mashup object

  1. Step 1: Define the mix

    // file
    export const mixin = {
        // pull back (of a key (in music)
        methods:{
            showName(){
                alert()
            }
        }
    
    }
    
  2. Step 2: Component Configuration

    <script>
    
    // Import the mixin
    import {mixin} from "@/mixin";
    
    export default {
      name: "StudentComp", data: function () {
      data: function () {
        return { name: "vue", address: "Beijing"}
      }, // Configure mixins (localized mixins).
      // Configure mixins (localized mixins), imported mixin
      // If there is more than one , the array can be configured with more than one
      mixins:[mixin]
    
    }
    
    
    </script>
    
    (mixin) // global mixin
    
  3. Part III: Normal Use

        <button @click="showName"> button</button>
    
  4. A mixin object can alarm data, methods, computed, and other component options.

    Theoretically you can component configure all options to be used, template and el may have certain limitations and merging issues

    export const mixin = {
        // callbacks
        methods: {
            showName() {
                alert()
            }
        },
        mounted() {
            ("test")
        }, data() { ("test")
        data() {
            // If the mixin and the data inside the component use the same attributes, the inside of the component takes precedence, if not, the two are combined
            return {baseUrl: "xxxx"}
        },
        // computed
        computed:{
    
        }, // computed: {baseUrl: "xxxx"} }
    
    }
    

plug-in (software component)

  1. Function: Used to enhance Vue

  2. Essence: an object containing the install method, where the first argument to install is Vue and the second later argument is the data passed by the plugin user

  1. Defining plug-ins

    export const TestPlugins = {
      // If you need to customize the parameters, just pass them after Vue
        install(Vue){
          // You can customize some of the methods
            // Filters
            ()
            // Mix-ins
            ()
    
            // Add methods to the Vue prototype (works for both vm and vc)
             = ()=>{}
        }
    }
    
  2. Using plug-ins

    import {TestPlugins} from "@/plugins";
    
    (TestPlugins)
    

scoped style

Multiple different components to write the style, selector is ultimately summarized together, there may go out class name, ID name conflict, scoped can make the style in the local effect, to prevent conflicts, the principle is to add a data-v-xxxxx, a unique identification on the corresponding element

<style scoped ></style>

Componentized coding process

  1. Implementing static components: extracting components, using components to achieve static page effects
    • Split static components: components should be split according to function points, naming should not conflict with html elements
  2. Display dynamic data: data type, name, which component to save it in, etc.
    • Consider where the data is stored, whether the data is used by one component or a number of components
    • A component in use: just put it on the component itself
    • Some components in use: placed on their common parent (state elevation)
  3. Interaction: Binding event listeners, etc.
  4. props applies to.
    • Parent component ==> child component Communication
    • Child component ==> Parent component Communication (requires the parent to give the child a function first)

Browser Local Storage

The size of the stored content generally supports about 5MB (this may vary from browser to browser).

  1. LocalStorage

    The content stored in LocalStorage needs to be cleared manually before it disappears, closing the browser will not disappear.

        // Local Storage - > Store to Local Storage
        // Both key and value are strings, if value is not a string, the toString method will be called by default.
        // If the key already exists, update the data
        ("name", "vue")
    
        // Read the data, if the key doesn't exist, read null.
        ("name")
    
        // Delete the data
        ("name")
    
        // Empty data - all data
        ()
    
  2. sessionStorage

    Content stored in SessionStorage disappears when the browser window is closed.

        // Local Storage -> Store to Session Storage
         ("name", "vue")
    
        // Read the data, if the key is not present, it will be null.
        ("name")
    
        // Delete the data
        ("name")
    
    
        // Empty data - all data
        ()
    

Custom Events for Components

In Vue, component custom events are an important mechanism for communication between components. It allows child components to pass information to the parent component. When some operation or state change occurs in a child component, the parent component can be notified by triggering a custom event.

For example, in an application that contains a form component (child component) and a display data component (parent component), after the user submits data in the form component, the form component can pass the data to the parent component via a custom event for subsequent processing by the parent component

Passing data through custom events
  1. Defining Custom Events - First Way
<template>

  <div>
    <! -- Binds an event to Student, the component instance object Vc -- >!
    <! -- Binds an event to whoever is looking to trigger the event -- >!
    <! -- v-on:custom event name = "corresponding method" -->!
    <! -- If you want the custom event to trigger only once, you can use the once modifier, or the $once method -->!
    <! -- It can be abbreviated as @testDemo="demo" -->
    <Student v-on:testDemo="demo"> </Student>
  </div>
</template>

<script>


import Student from "@/components/";

export default {
  name: 'App',
  components: {
    Student
  }, methods: { Student
  methods: {
    demo(name) {
      ("Subcomponent data name", name)
    }
  }
}
</script>
  1. Defining Custom Events - Second Way
<template>
  <div>
<! -- Setting the ref attribute to a component -->
    <Student ref="student"> </Student>
  </div>
</template>

<script>.


import Student from "@/components/";

export default {
  name: 'App',
  components: {
    Student
  }, methods: { Student
  methods: {
    demo(name) {
      ("Subcomponent data name", name)
    }
  }, }
  // When the component is loaded
  mounted() {
    // student component instance object, bind testDemo event, trigger Demo callback.
    // For more flexibility, you can do some backward and forward manipulation before binding the event.
    // This way the callback is either configured in methods or in an arrow function, where this is the component instance to bind to
    this.$. $on("testDemo",)
  }
}
</script>
  1. Triggering custom events
<script>
 export default {
   name: "Student",
  data: function () {
    return {name: "vue", address: "Beijing"}
  },
  methods: {
    sendStudentName(){
      // pass (a bill or inspection etc)$emitmethod triggers an event,Pass in the name of the custom event
      // trigtestDemoevent
      this.$emit("testDemo",)
    }
  }
}


</script>

<template>
   <div class="student">
    <h1>name (of a person or thing):{{ name }}</h1>
    <h1>address:{{ address }}</h1>
    <button @click="sendStudentName">buttons</button>

  </div>


</template>
Unbinding custom events
// Call unbind the specified component on the component to be unbound
this.$off("testDemo")
// Unbind multiple specified events
this.$off(["testDemo", "xxxx"])
// All custom events are unbound
this.$off()
native

If a native event is bound to a component tag, the component tag will also treat the custom event as if it were looking for a custom method

<! -- Use the native modifier to tell the component that this is a native event -->
<Student ref="student" @="show"></Student>

global event bus

A way of inter-component communication , used for arbitrary inter-component communication , the implementation of the event communication mechanism in the application , which allows decoupled communication between different components . Think of it as a message center , each component or module can publish (trigger) events to this center , you can also subscribe to (listen to) events from this center . When an event is published, all components or modules subscribed to the event will be notified and can perform the corresponding action.

Creating a global event bus

.__proto__ ===

$on, $off, and $emit are all methods on the Vue prototype, and the component instance object (vc) can access the properties and methods on the Vue prototype

This can be used as a global event bus by creating a new instance of Vue. This is usually set up in the project's entry file

// Entry file
new Vue({
    render: h => h(App), // lifecycle function: beforeCreate The component instance is called when it is first created.
    // Lifecycle function: beforeCreate Called when the component instance is first created.
    beforeCreate() {

        // Add a $bus attribute to the vue prototype with the value of the current vue instance.

         . $bus = this
    }
}). $mount('#app')
Using the Global Event Bus

Receiving data: if component A wants to receive data, it binds a custom event to $bus in component A. The callback of the event stays in component A itself.

// Subcomponent A
// Bind events after the component is mounted
mounted() {
    // Bind a test event on bus(vue)
    this.$bus.$on("test",(data)=>{
      ("Received data",data)
    })
  },
 // Unbinding before component destruction
    beforeDestroy(){
      this.$bus.$off("test")
    }

Trigger the global event bus
// Subcomponent B
sendData(){
      // Trigger the test event on bus(vue).
      this.$bus.$emit("test", "data data")

    }

Message subscription and publishing

The concept of PubSub
  • PubSub is an acronym for Publish - Subscribe, which is essentially a messaging model. In this model, there are two types of roles, Publishers and Subscribers. Publishers are responsible for generating messages and sending them to a message center (also known as a Message Broker), while Subscribers express their interest in certain message types to the message center, and when the message center receives a message from a Publisher that matches a Subscriber's interest, it forwards the message to the Subscriber.

  • A way of inter-component communication, applicable to any inter-component communication

  • There are a number of specialized PubSub libraries that can help with message publishing and subscribing. For example the pubsu-js library

Using pubsub
  1. Installing the pubsu-js library

    npm install -g pubsub-js       
    
  2. Introduction of pubsub

    import pubsub from 'pubsub-js'
    
  3. Subscribe to messages

    If component A wants to receive data, it subscribes to the message in component A. The subscription callback stays in component A itself.

    // Subscribe to messages after the component is mounted
    mounted() {
        // Parameters: topic, callback function (topic name, data).
        // Subscribes to the testTopic topic, so if someone sends a message to the testTopic topic, it will receive it.
        // will return a subscription id
         = ("testTopic",function (msgName,data){
          // This is undefined because we're using a third-party library.
          // You can use an arrow function where this is the current vc or configure a callback function to be called from here.
          (data)
    
        })
      }, // Before the component is destroyed, this is undefined.
        // Before the component is destroyed
      beforeDestroy(){
        // Unsubscribe (subscription id)
        ()
      }
    
  4. post a message

        // Send a message to the subscribed testTopic topic with the message helloworld
        ("testTopic", "helloworld")
    

$nextTick

$nextTickis an instance method provided by Vue whose main purpose is to execute a delayed callback after the next DOM update loop ends. In Vue, the change of data to DOM update is asynchronous. When the data changes, Vue will open an asynchronous update queue to merge all the DOM update operations caused by data changes in the same event loop into one update task, and then execute the DOM update at once when the current round of the event loop ends.$nextTickis used to perform some actions after this DOM update is complete

     edit(todo){
       if(('isEdit')){
         = true
      }else {
        this.$set(todo,'isEdit',true)
      }
       this.$()
     }
// Example problem: We want to change a state so that the input box gets focus when the state is true.
// The problem is that vue doesn't render immediately after the = true change, it waits until all the code has been executed.
// It's equivalent to this.$() being executed and then rendering it.
// The page isn't rendered yet, it's false, and getting focus fails.
// When the page has finished rendering, then get the focus
this.$nextTick(function (){
        this.$()
      })
  1. Purpose: Execute the callback specified by it at the end of the next DOM update.

  2. When to use: When changing data, to perform some operations based on the updated new DOM, in the callback function specified by nextTick

Transitions and animations

Adds a style class name to an element at the appropriate time when inserting, updating, or removing a DOM element

image-20241121135250739

Animated Default Name Effect

vue automatically implements animation effects based on rules that apply an animation

<template>
  <div>
    <button @click="isShow = !isShow"> show/hide</button>
    <! -- Wrap whoever is animated with transition -->!
    <! -- The appear attribute is used to control whether or not a transition is applied to an element at initial rendering Without it, the initial rendering is not applied -->!
    <! -- Applies only to wrapping a single element --> <!
    <transition appear>
      <h1 v-show="isShow"> hello world</h1>

    </transition>

  </div>.
</template>.

<style scoped>.
h1 {
  background-color: orange;
}

/* v-enter-active is mainly used to define the behavior of the transition animation when an element is entered (inserted) */
.v-enter-active {
  animation: test 1s; }
}

/* v-leave-active is used to define the behavior of the transition animation when an element leaves (removes) */
.v-leave-active {
  animation: test 1s reverse; }
}

/* Define animation keyframes */
@keyframes test {
  from {
    transform: translateX(-100%); }
  }
  to {
    transform: translateX(0px); } to { transform: translateX(0px); }
  }

}
</style>.
Animated Custom Names

Setting a custom name allows you to specify several different effects

<!-- indicate clearly and with certaintynamename (of a thing)-->
<transition appear name="hello">
      <h1 v-show="isShow">hello world</h1>
 
    </transition>
/* Using the specifiedname */
.hello-enter-active {
  animation: test 1s;
}

/* Using the specifiedname */
.hello-leave-active {
  animation: test 1s reverse;
}
transition effect
<template>
  <div>
    <button @click="isShow = !isShow"> show/hide</button>
    <! -- Wrap whoever is animated with transition -->!
    <! -- The appear attribute is used to control whether or not a transition is applied to an element at initial rendering, without which it is not applied at initial rendering -- &>!
    <transition appear>.
      <h1 v-show="isShow"> hello world</h1>

    </transition>

  </div>.
</template>.

</style scoped> </div> </template>

h1{
  background-color: orange;
  transition: 0.5s linear;
}
/* Starting point of entry */
.hello-enter {
  transform: translateX(-100%); }
}

/* The end point of the entry */
.hello-enter-to {
  transform: translateX(0); }

}

/* Starting point for leaving */
.hello-leave{
  transform: translateX(0%);

}

/* The end point of the leave */
.hello-leave-to{
  transform: translateX(-100%);

}
</style>.

merged writing

h1{
  background-color: orange;
}

/* Starting point for entering and ending point for leaving */
.hello-enter,.hello-leave-to {
  transform: translateX(-100%); }
}

/* Without modifying the style of the h1 itself, set the effect when using enter and leave */
.hello-enter-active,.hello-leave-active {
  transition: 0.5s linear;
}

/* End of entry and start of leave */
.hello-enter-to,.hello-leave {
  transform: translateX(0); }

}
Multiple element transitions
<! -- transition can only wrap an element -->!
<! -- Wrapping multiple elements uses transition-groups and each element has a key value -->
    <transition-group appear name="hello">
      <h1 v-show="isShow" key="1">hello world</h1>
      <h1 v-show="isShow" key="2">hello vue</h1>
      <h1 v-show="isShow" key="3">hello html</h1>

    </transition-group>
Integration of third-party animations

The effect can be achieved using an off-the-shelf three-way animation library

animate animation library documentation (wall)

  1. mounting

    npm install  --save
    
  2. pull into

    import ""
    
    
  3. configure

        <! -- Configuration name -- >;!
        <! -- configure the effect to enter Choose the name of the corresponding effect on the library's documentation -- >!
        <! -- configure the exit effect Choose the name of the corresponding effect on the library's documentation -- > <!
    
        <transition-group
            name="animate__animated
            name="animate__animated animate__bounce"
            enter-active-class="animate__bounceOutRight"
            leave-active-class="animate__fadeInDown"
        >.
          <h1 v-show="isShow" key="1">hello world</h1>
          <h1 v-show="isShow" key="2">hello vue</h1>
          <h1 v-show="isShow" key="3">hello html</h1>
    
        </transition-group>