"Vue.js Actual Warfare Records

Code example reference:


webpack Project Example Reference:


Initial knowledgeVue.js

It provides common advanced features in modern Web development:

  • Decoupling views and data
  • Reusable components
  • Front End Routing
  • State Management
  • Virtual DOM



Insert Html


The character inside the decorated element will not be compiled and converted


> :

Dynamically update attributes of HTML or component elements, such as id,class,href,src, etc.

How v-bind binds class es:

  1. Object Grammar

    <div :class="{'active': isActive}"></div>

    Render as <div class="active"></div>when isActive is true

  2. Array syntax

    <div> :class="[activeCls, errorCls]"</div>
    date: {
    	activeCls: 'active',
    	errorCls: 'error'

    Rendered as <div class="active error"></div>

Inline style style is the same as class usage.


> @

Listen for native DOM events

Event modifiers (which can be concatenated), such as
 .stop, stop click event bubble?
@Submi.preventSubmit the event without overloading the page
 @click.once, triggered only once
 @Click.nativeThat modifies a native event

For @keyCode, including, but not limited to:


It will be removed from the bound html element at the end of the Vue instance compilation, andDisplay:noneCooperative use Main solution whenVue.jsWhen not loaded, the text {{xxx}} appears on the page, flashes over, and will not be replaced until the Vue creates the instance, which can be viewed at F5 consecutively.

<style type="text/css">
        [v-cloak] {
            display: none;
<div id="app" v-cloak>


After the first rendering, it is no longer re-rendered as the data changes and is considered static content, which is used when optimization is required. v-if,v-else-if,v-else conditional rendering


Show when true.Change the css attribute display of the element. Compared with v-if, it is suitable for scenarios with frequent switching conditions.


Modified elements are rendered circularly.Usage such as:

        <li v-for="book in books">{{ book.name }}</li>



When using the Chinese input method, the data will not be bound in real time without word selection.You can do this with @input, as follows

<input type="text" @input="handleInput" placeholder="Real-time input.">
<h1>Not yet selected words will also be shown:{{ message }}</h1>

methods: {
	handleInput: function (e) {
	this.message = e.target.value;

Similar to event v-on(@), v-model(:) also has modifiers to control when data is synchronized.


<input type="text" v-model.lazy="namee" placeholder="Your Name">

Not real-time changes, but updates when you lose focus or return


Convert input to Number type


Automatically filter first and last spaces of input

Custom directives

Global directives

Vue.directive('focus', {
	// Instruction Options

Local directives

var app = new Vue({
	el: '#app',
	directives: {
		focus: {
			// Instruction Options

Render the page so that input gets the focus.

<input type="text" v-focus>

Vue.directive('focus', {
	inserted: function (el) {


  • bind, the first binding to an element is a call
  • Inserted, called when a bound element is inserted into a parent node, for example, when rendering a page
  • Update, called on the last update where the bound element is located
  • componentUpdated, called when the template containing the bound element completes an update cycle
  • unbind, called when an instruction is unbound from an element

Parameters of hook function

  • el, the element bound by the directive, which can be used to manipulate the DOM directly
  • binding, including the following properties
    • Name, instruction name, not including v-prefix, e.g. v-focus, name is focus
    • Value, the value bound by the instruction, such as v-focus="1+1", value 2
    • oldValue, the previous value of the directive
    • Expression, the binding is worth string form, such as v-focus="1+1", expression is "1+1"
    • Arg, the parameter passed to the instruction, such as v-focus:foo, arg is foo
    • Modifiers, an object containing modifiers, such as v-focus.foo.bar, modifiers is {foo: true, bar: ture}
  • vnode, virtual node generated by Vue compilation
  • oldVnode, last virtual node

Computing attributes


Can only be used as an attribute, not'()', i.e. parameter cannot be sent.

The difference between computed and methods is:

  1. Unable to accept parameters

  2. When used as an attribute, not a method, you cannot add'()'

  3. Calculated properties are based on dependent caches, for example, Calculation Date.now(), does not refresh, but on methods.

     <div> {{ now }}</div>
     <div> {{ nowDate() }}</div>
         // Computing attributes
         computed: {
             now: function () {
                 return Date.now();
         methods: {
             nowDate: function () {
                 return Date.now();

Forms and v-model s

radio button

<input type="radio" v-model="picked" value="html" id="id_html">
<label for="html">HTML</label>
<input type="radio" v-model="picked" value="js" id="id_js">
<label for="js">javaScript</label>
<p>The selected item is: {{ picked }} </p>

picked: "js"

check box

  • Bind a Boolean value with v-model when used individually

  • When combined, bind to the same array type

    <input type="checkbox" v-model="checked" value="html" id="id_html">
    <label for="html">HTML</label>
    <input type="checkbox" v-model="checked" value="js" id="id_js">
    <label for="js">javaScript</label>
    <p>The selected item is: {{ checked }} </p>
    checked: []

Selection list (drop-down box)

<select v-model="selected" multiple>
	<option value="js">javaScript</option>
	<option value="css">css</option>
<p>The selected item is: {{ selected }} </p>

selected: []


Global Components

Vue.component('my-component', {
	template: '<div>Component Content</div>'

Local Components

var Child = {
	template: '<div>Component Content</div>'

var app = new Vue({
	el: '#app',
	component: {
		'my-component': Child

Component Data and Methods

When using data, unlike the Vue instance, the data must be a function and then return the data.

Vue.component('my-component', {
	template: '<div>{{ message }}</div>',
	data: function () {
		return {
			message: 'Component Content'

Transferring data using props

The parent component contains child components, and the parent component is forwarding data or parameters, which is achieved through props.

> The changes to Vue 2.x and Vue 1.x are that props pass data in one direction and only forward to subcomponents.Decouple parent-child components whenever possible. > > Vue 1.x provides the.sync modifier to support bidirectional binding.

In a component, the props option declares data to be accepted from the parent, which can be:

  1. array

    <!-- html Case insensitive. Naming must be separated by a horizontal bar -->
    <!-- The data passed in is usually not written to death, but dynamic data from the parent, using v-bind To dynamically bind. -->
    <input type="text" v-model="parentMessage">
    <my-component :props-message="parenMessage"></my-component>
    Vue.component('my-component', {
    	// Must be named after a hump
    	props: ['propsMessage'],
    	template: '<div>{{ propsMessage }}--{{ message }}</div>',
    	data: function () {
    		return {
    			message: 'Component Content'
  2. object

    Object Writing is required when prop needs validation.

    props: {
    	propsMessage: {
    		type: Boolean,
    		default: true

    Typee type s can be:







Component Communication

Custom Events

Use this. $emit ('increase') in the component.This.counter; trigger events

Use <my-component @increase="handleIncrease"></my-component> to accept events and process them in handleIncrease where components are used.

Where,This.counterRepresents the data that is passed from the component and will be used as a parameter to the handleIncrease as follows:

function handleIncrease (counter) {} 

>Grammatical sugar: > >Use this. $emit ('input') in the component.This.counter; trigger events > >Use <my-component v-model="currentCounter"></my-component> > >You can then reverse-bind the subclass data to the currentCounter of the parent component.

Non-parent-child component communication

Vue.js 1.x

$.dispatch() and $broadcast() are provided inVue.js2.x Waste

Use this.$dispatch('on-message','data for internal components') within a component; send events

Vue.js 2.x

1. Use a central event bus

>When the project is large, you can choose a better state management solution vuex

var bus = new Vue();

Vue.component('my-component', {
	template: '<button @click="handleEvent">Delivery Event</button>',
	methods: {
        handleEvent: function () {
            bus.$emit('on-message', 'Come from my-component Component data');

var app = new Vue({
    el: '#app',
    data: {
        message: ''
    mounted: function () {
        var _this = this;
        bus.$on('on-message', function (msg) {
            _this.message = msg;
2. Parent Chain

Use this. $directly in subcomponentsParent.message, message represents a variable above the parent.

Or use the parent component, this.$children.message

>Parent chains make parent-child components tightly coupled, preferably communicating through props and $emit.

3. Subcomponent Index

Add ref attribute when using components

<my-component ref="comA"></my-component>

Use this. $Refs.comA.messageGets the component's internal data, and the message represents the component's internal variables.

Distributing content using slot s

> Content distributed by slot, scoped on the parent component. > >People: slot distribution refers to content within a component, such as <my-component><p>content</p></my-component>, where'<p>content</p>'denotes content to be distributed; distribution refers to content that will be inserted into subcomponents.The scope of this compiled content is the parent component, not the child component.



methods: {
	getText: function () {
		this.$nextTick (function () {
			var text = document.getElementById('div').innerHTML;

>Because Vue updates DOM principle asynchronously.Instead of updating the DOM directly, Vue opens a queue and buffers it in the same event loop. In the next event loop tick, Vue refreshes the queue and performs the actual work.

$nextTick indicates execution in the next event loop.

Manually mount components

new MyComponent().$mount('#mount-div');

Using Webpack 2

>Single Page Rich Applications (SPA) is an application with only one Web page.A single-page application (SPA) is a Web application that loads a single HTML page and dynamically updates it when a user interacts with the application. > >Baidu Encyclopedia https://baike.baidu.com/item/SPA/17536313?fr=aladdin

Vue Project Configuration

New directory demo directory

npm init will generate aPackage.jsonfile

npm init

Install webpack locally

npm install webpack --save-dev
Using the command--save, or not writing--save, records information in dependencies
 dependencies records all the files the project needs to run
 Use the command--save-dev to record information in devDependencies
 The devDependencies record files that the project needs to use during development, but not when it is ultimately published

>--save and--save-dev: > > https://blog.csdn.net/cvper/article/details/88728505

Install webpack-dev-server locally, which provides many services, such as starting a server, hot updates, and interface proxies.

npm install webpack-dev-server --save-dev


npm install webpack-cli

Package.jsonFile contents:

  "name": "demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-dev-server": "^3.11.0"
  "dependencies": {
    "webpack-cli": "^3.3.11"

The webpack is a.js configuration file.

New emptyMain.jsFile, as the entry file.

new fileWebpack.config.jsAs follows

var path = require('path');

var config = {
	entry: {
		main: './main'
	output: {
		// Specify output directory for packaged files
		path: path.join(__dirname, './dist'),
		// Specify the directory referenced by the resource file
		publicPath: '/dist/',
		// Specify the name of the output file
		filename: 'main.js'

module.exports = config;

Newly buildIndex.htmlAs an entry to SPA

    <meta charset="utf-8">
    <title>webpack App</title>

	<div id="app">
		Hello World.
	<script type="text/javascript" src="/dist/main.js"></script>

To configurePackage.json, when npm run dev is run, the command is executed.The default address is

  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1",
	"dev": "webpack-dev-server --open --config webpack.config.js"

Start with command

npm run dev

stayMain.jsFile, add, save, browser will display changes in real time, this is the hot update function of webpack-dev-server.

document.getElementById('app').innerHTML = 'Hello webpack';

Perfect project configuration

Different modules in a webpack require different loaders to handle them.

npm install css-loader --save-dev
npm install style-loader --save-dev

Refer specifically to the demo folder:


Not finished.

> "Vue.js Actual War Liang Hao

Tags: Programming Vue Webpack npm Attribute

Posted on Sun, 07 Jun 2020 12:51:44 -0400 by xec