vue.js note taking

Zero and preamble

Vue.js (pronunciation / vju ː /, similar to view) is a progressive framework for building user interface.

Vue adopts the design of bottom-up incremental development, and the core library of Vue only focuses on the view layer.

The goal of Vue.js is to implement the data binding and combined view components of the response through the simplest possible API.

I. Vue.js template syntax

Vue.js uses HTML based template syntax, which allows developers to declaratively bind DOM to the data of the underlying Vue instance.

At the heart of Vue.js is a system that allows you to declaratively render data into the DOM using concise template syntax.

Combined with the response system, when the application state changes, Vue can intelligently calculate the minimum cost of re rendering components and apply it to DOM operations.

The most common form of data binding is text interpolation using {{...}} (double braces)

Using v-html instruction to output HTML code

<div id="app">
    <div v-html="message"></div>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    message: '<h1>Green hand</h1>'
  }
})
</script>

attribute

The value in the HTML attribute should use the v-bind directive.

<div id="app">
  <label for="r1">Modify color</label>
  <input type="checkbox" v-model="use" id="r1">
  <br><br>
  <div v-bind:class="{'class1': use}">
    v-bind:class instructions
  </div>
</div>
    
<script>
new Vue({
    el: '#app',
  data:{
      use: false
  }
});
</script>

The v-model instruction is used to create a two-way data binding on the input, select, textarea, checkbox, radio and other form control elements, and automatically update the values of the bound elements according to the values on the form.

Button events we can use v-on to listen for events and respond to user input.

2. Vue.js conditions and cycles

1. Condition judgment

1,v-if

Condition judgment uses v-if instruction:

<div id="app">
    <p v-if="seen">Now you see me</p>
    <template v-if="ok">
      <h1>Rookie tutorial</h1>
      <p>What we learn is not only technology, but also dream!</p>
      <p>Ha ha ha, typing hard!!!</p>
    </template>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    seen: true,
    ok: true
  }
})
</script>

2,v-else

You can use the v-else instruction to add an "else" block to v-if:

div id="app">
    <div v-if="Math.random() > 0.5">
      Sorry
    </div>
    <div v-else>
      Not sorry
    </div>
</div>
    
<script>
new Vue({
  el: '#app'
})
</script>

3,v-else-if

v-else-if is added in 2.1.0. As the name implies, it is used as the else if block of v-if. Multiple use of chain

<div id="app">
    <div v-if="type === 'A'">
      A
    </div>
    <div v-else-if="type === 'B'">
      B
    </div>
    <div v-else-if="type === 'C'">
      C
    </div>
    <div v-else>
      Not A/B/C
    </div>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    type: 'C'
  }
})
</script>

4,v-show

We can also use the v-show instruction to display elements according to conditions:

div id="app">
    <h1 v-show="ok">Hello!</h1>
</div>
	
<script>
new Vue({
  el: '#app',
  data: {
    ok: true
  }
})
</script>

5, pay attention to

1. Differences between v-if and v-show

1. v-if controls the removal / addition of DOM, and v-show controls the display of DOM style.

2. Use v-show when frequently switching between display and hide (because v-if is frequently used to remove / add transition loss performance).

3. Use v-if when judging only once.

2. Change array

1. The array cannot be changed by index, so it will not be rendered.

2. You cannot change the array by changing its length, so it will not render.

3. Mutation array methods: push, pop, shift, unshift, sort, reverse, splice.

3. Change object

1. Adding or deleting attributes to the object will not render the page.

2,vm.$set().

2. Circular statement

Loop the v-for instruction.

The v-for instruction needs a special syntax in the form of site in sites, which is the source data array and site is the alias of array element iteration.

<div id="app">
  <ol>
    <li v-for="site in sites">
      {{ site.name }}
    </li>
  </ol>
</div>
 
<script>
new Vue({
  el: '#app',
  data: {
    sites: [
      { name: 'Runoob' },
      { name: 'Google' },
      { name: 'Taobao' }
    ]
  }
})
</script>

1. v-for iteration object

v-for can iterate data through the properties of an object:

<div id="app">
  <ul>
    <li v-for="value in object">
    {{ value }}
    </li>
  </ul>
</div>
 
<script>
new Vue({
  el: '#app',
  data: {
    object: {
      name: 'Green hand',
      url: 'http://www.runoob.com',
      slogan: 'What we learn is not only technology, but also dream!'
    }
  }
})
</script>

You can also provide the second parameter as the key name:

<div id="app">
  <ul>
    <li v-for="(value, key) in object">
    {{ key }} : {{ value }}
    </li>
  </ul>
</div>

The third parameter is the index:

Index starts from 0 when index is index

Note the order of v-for loop parameters (value,key,index)

The order of the parameters of the cycle is opposite to the order of the output

<div id="app">
  <ul>
    <li v-for="(value, key, index) in object">
     {{ index+1 }}. {{ key }} : {{ value }}
    </li>
  </ul>
</div>

2. v-for iterative integer

v-for can also loop integers

When iterating, n starts at 1

<div id="app">
  <ul>
    <li v-for="n in 10">
     {{ n }}
    </li>
  </ul>
</div>

III. Calculation properties of Vue.js

Calculation attribute keyword: calculated.

<div id="app">
  <p>Original string: {{ message }}</p>
  <p>Reverse string after calculation: {{ reversedMessage }}</p>
</div>
 
<script>
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  computed: {
    // getter of calculated property
    reversedMessage: function () {
      // `this' points to vm instance
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

1,computed vs methods

We can use methods instead of computed. The effect is the same for both methods, but computed is based on its dependency cache, and only when the relevant dependency changes will it be revalued. With methods, when rendering again, the function will always call and execute again.

<div id="app">
  <p>Original string: {{ message }}</p>
  <p>Reverse string after calculation: {{ reversedMessage }}</p>
  <p>Reverse string after using method: {{ reversedMessage2() }}</p>
</div>

<script>
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  computed: {
    // getter of calculated property
    reversedMessage: function () {
      // `this' points to vm instance
      return this.message.split('').reverse().join('')
    }
  },
  methods: {
    reversedMessage2: function () {
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

If the code is changed, the concept of computer property "dependent cache" and the difference with method should be reflected. As the following code, cnt is a variable independent of the vm object. When using the calculation property of reversedMessage, the code will be executed for the first time to get a value, and then the calculation property of reversedMessage will be used later. Because the vm object has not changed, the interface rendering will use the value directly, and the code will not be executed repeatedly. But reversedMessage2 does not have this cache. As long as it is used once, the function code will execute once, so each return value is different.

var cnt=1;
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  computed: {
    // getter of calculated property
    reversedMessage: function () {
      // `this' points to vm instance
      cnt+=1;
      return cnt+this.message.split('').reverse().join('')
    }
  },
  methods: {
    reversedMessage2: function () {
      cnt+=1;
      return cnt+this.message.split('').reverse().join('')
    }
  }
})

When you don't use the dependency cache of calculation properties, you can use the definition method instead of calculation properties. Defining a method in methods can achieve the same effect, and even the method can accept parameters, which is more flexible to use.

IV. Vue.js listening properties

Vue.js listens to the watch attribute, which we can use to respond to data changes.

For example, the conversion between KM and M is carried out:

<div id="app">
			//Km: < input type = "text" V-model = "kilometers" / >
			//Meters: < input type = "text" V-model = "meters" / >
			<p id="info"></p>
		</div>
		
		<script>
			var vm=new Vue({
				el:'#app',
				data:{
					kilometers:0,
					meters:0
				},
				watch:{
					kilometers:function(val){
						this.kilometers=val;
						this.meters=this.kilometers*1000;
					},
					meters:function(val){
						this.kilometers=val/1000;
						this.meters=val;
					}
				}
			});
			vm.$watch('kilometers', function (newValue, oldValue) {
				document.getElementById ("info").innerHTML = "The value before modification is: " + oldValue + ",The modified value is: " + newValue;
			})
		</script>

A simple shopping cart is implemented through vue monitoring event:

div id="app">
    <table>
    <tr>
        <th>Serial number</th>
        <th>Trade name</th>
        <th>commodity price</th>
        <th>Purchase quantity</th>
        <th>operation</th>
    </tr>
    <tr v-for="iphone in Ip_Json">
        <td>{{ iphone.id }}</td>
        <td>{{ iphone.name }}</td>
        <td>{{ iphone.price }}</td>
        <td>
        <button v-bind:disabled="iphone.count === 0" v-on:click="iphone.count-=1">-</button>
        {{ iphone.count }}
        <button v-on:click="iphone.count+=1">+</button>
        </td>
        <td>
        <button v-on:click="iphone.count=0">remove</button>
        </td>
    </tr>
    </table>
    Total price: ${{totalPrice()}}
</div>

<style>
	table {
    border: 1px solid black;
	}
	table {
   	width: 100%;
	}

	th {
    height: 50px;
	}
	th, td {
    border-bottom: 1px solid #ddd;
	}
</style>
var app = new Vue({
  el: '#app',
  data: {
    Ip_Json: [{
      id: 1,
      name: 'iphone 8',
      price: 5099,
      count: 1
    },
              {
                id: 2,
                name: 'iphone xs',
                price: 8699,
                count: 1
              },
              {
                id: 3,
                name: 'iphone xr',
                price: 6499,
                count: 1
              }]

  },
  methods:{
    totalPrice : function(){
      var totalP = 0;
      for (var i = 0,len = this.Ip_Json.length;i<len;i++) {
        totalP+=this.Ip_Json[i].price*this.Ip_Json[i].count;
      }
      return totalP;
    }


  }
})

V. Vue.js style binding

1,Vue.js class

class and style are the attributes of HTML elements. They are used to set the style of elements. We can use v-bind to set the style attributes.

Vue.js v-bind specifically enhances it when dealing with class and style. The result type of an expression can be an object or an array in addition to a string.

1. class attribute binding

We can set an object for v-bind:class to dynamically switch class:

<style>
.active {
    width: 100px;
    height: 100px;
    background: green;
}
.text-danger {
    background: red;
}
</style>
</head>
<body>
<div id="app">
  <div class="static"
     v-bind:class="{ 'active': isActive, 'text-danger': hasError }">
  </div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
    hasError: true
  }
})
</script>

2. Array syntax

<div id="app">
	<div v-bind:class="[activeClass, errorClass]"></div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
</script>

3. Triple expression to switch class in the list

<div id="app">
    <div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})

2. Vue.js style

<div id="app">
	<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">Rookie tutorial</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    activeColor: 'green',
	fontSize: 30
  }
})
<div id="app">
  <div v-bind:style="styleObject">Green hand</div>
</div>
​
<script>
new Vue({
  el: '#app',
  data: {
    styleObject: {
      color: 'green',
      fontSize: '30px'
    }
  }
})

Vi. Vue.js form

You can use the v-model directive to create two-way data bindings on form control elements.

v-model automatically selects the correct method to update the element according to the control type.

<div id="app">
  <input type="radio" id="runoob" value="Runoob" v-model="picked">
  <label for="runoob">Runoob</label>
  <br>
  <input type="radio" id="google" value="Google" v-model="picked">
  <label for="google">Google</label>
  <br>
  <span>The selected value is: {{ picked }}</span>
</div>
 
<script>
new Vue({
  el: '#app',
  data: {
    picked : 'Runoob'
  }
})
</script>

1. Modifier

1,.lazy

By default, v-model synchronizes the value and data of the input box in the input event, but you can add a modifier lazy to change it to synchronize in the change event:

<! -- update in "change" instead of "input" event -- >
<input v-model.lazy="msg" >

2,.number

If you want to automatically convert the user's input value to the number type (return the original value if the conversion result of the original value is NaN), you can add a modifier number to v-model to process the input value:

<input v-model.number="age" type="number">

This is usually useful because the value entered in HTML also always returns a string type when type = number.

3,.trim

If you want to automatically filter the first and last spaces of user input, you can add trim modifier to v-model to filter input:

<input v-model.trim="msg">

VII. Vue.js component

Component is one of the most powerful functions of Vue.js.

Components can extend HTML elements and encapsulate reusable code.

Component system allows us to build large-scale applications with independent and reusable small components. Almost any type of application interface can be abstracted as a component tree:

The syntax format of registering a global component is as follows:

Vue.component(tagName, options)

tagName is the component name and options is the configuration option. After registration, we can call components in the following ways:

<tagName></tagName>

1. Global components

Global components are available for all instances.

div id="app">
    <runoob></runoob>
</div>
 
<script>
// register
Vue.component('runoob', {
  template: '<h1>Custom components!</h1>'
})
// Create root instance
new Vue({
  el: '#app'
})
</script>

2. Local components

We can also register the local component in the instance option, so that the component can only be used in this instance:

	<div id="app">
			<add></add>
			<tdc></tdc>
		</div>
		<script>
			/*Global component registration*/
			Vue.component('add',{
				template:'<h1>I am there.</h1>'
			});

			/*Local component registration*/
			new Vue({
				el:'#app',
				data:{},
				components:{
					'tdc':{
						template:'<h1>I'm hijacking the course</h1>'
					}
				}
			});
		</script>

3,Props

props is a custom property used by the parent component to pass data.

The data of the parent component needs to be passed to the child component through props. The child component needs to explicitly declare "props" with the props option

<div id="app">
    <child message="hello!"></child>
</div>
​
<script>
// register
Vue.component('child', {
  // Statement props
  props: ['message'],
  // It can also be used in vm instance like "this.message"
  template: '<span>{{ message }}</span>'
})
// Create root instance
new Vue({
  el: '#app'
})
</script>

4. Dynamic Props

Similar to using v-bind to bind HTML features to an expression, you can also use v-bind to dynamically bind the value of props to the data of the parent component. Whenever the data of the parent component changes, the change is also transmitted to the child component.

<div id="app">
	<div>
	  <input v-model="parentMsg">
	  <br>
	  <child v-bind:message="parentMsg"></child>
	</div>
</div>

<script>
// register
Vue.component('child', {
  // Statement props
  props: ['message'],
  // It can also be used in vm instance like "this.message"
  template: '<span>{{ message }}</span>'
})
// Create root instance
new Vue({
  el: '#app',
  data: {
	parentMsg: 'Parent component content'
  }
})
</script>
<div id="app">
			<ul>
				<child-to v-for="site in sites" :message="site"></child-to>
			</ul>
		</div>
		
		<script>
			Vue.component('child-to',{
				props:['message'],
				template:'<li>{{message.text}}</li>'
			});
			
			new Vue({
				el:'#app',
				data:{
					sites:[
						{text:'baidu'},
						{text:'google'},
						{text:'chrome'}
					]
				}
			});
		</script>

Note: props are one-way bound: when the properties of the parent component change, they will be passed to the child component, but not vice versa.

5. Prop verification

Components can specify validation requirements for props.

To customize the verification method of props, you can provide an object with verification requirements for the values in props, rather than an array of strings. For example:

Vue.component('my-component', {
  props: {
    // Basic type check ('null' and 'undefined' will pass any type verification)
    propA: Number,
    // Multiple possible types
    propB: [String, Number],
    // Required string
    propC: {
      type: String,
      required: true
    },
    // Number with default
    propD: {
      type: Number,
      default: 100
    },
    // Objects with default values
    propE: {
      type: Object,
      // Object or array defaults must be obtained from a factory function
      default: function () {
        return { message: 'hello' }
      }
    },
    // Custom validation function
    propF: {
      validator: function (value) {
        // This value must match one of the following strings
        return ['success', 'warning', 'danger'].indexOf(value) !== -1
      }
    }
  }
})

6. User defined events

The parent component uses props to pass data to the child component, but if the fruit component wants to pass data back, it needs to use custom events!

We can use v-on to bind custom events. Each Vue instance implements the events interface, which is:

  • Use $on(eventName) to listen for events
  • Use $emit(eventName) to trigger events

In addition, the parent component can directly use v-on to listen for events triggered by the child component where the child component is used.

<div id="app">
	<div id="counter-event-example">
	  <p>{{ total }}</p>
	  <button-counter v-on:increment="incrementTotal"></button-counter>
	  <button-counter v-on:increment="incrementTotal"></button-counter>
	</div>
</div>

<script>
Vue.component('button-counter', {
  template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    incrementHandler: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})
</script>

1. data must be a function

In the above example, you can see that the data in the button counter component is not an object, but a function:

data: function () {
  return {
    count: 0
  }
}

The advantage is that each instance can maintain an independent copy of the returned object. If the data is an object, it will affect other instances, as shown below:

<div id="components-demo3" class="demo">
    <button-counter2></button-counter2>
    <button-counter2></button-counter2>
	<button-counter2></button-counter2>
</div>

<script>
var buttonCounter2Data = {
  count: 0
}
Vue.component('button-counter2', {
    /*
    data: function () {
	    // data Option is a function, components do not affect each other
        return {
            count: 0
        }
    },
    */
    data: function () {
        // The data option is an object that affects other instances
        return buttonCounter2Data
    },
    template: '<button v-on:click="count++">Click. {{ count }} Second time.</button>'
})
new Vue({ el: '#components-demo3' })
</script>

VIII. Vue.js custom instruction

In addition to the core instructions (v-model and v-show) set by default, Vue also allows you to register custom instructions.

1. Global instruction registration

<div id="app">
	<p>When the page is loaded, input Elements get focus automatically:</p>
	<input v-focus>
</div>

<script>
// Register a global custom instruction v-focus
Vue.directive('focus', {
  // When the binding element is inserted into the DOM.
  inserted: function (el) {
    // Focusing element
    el.focus()
  }
})
// Create root instance
new Vue({
  el: '#app'
})
</script>

2. Local instruction registration

<div id="app">
  <p>When the page is loaded, input Elements get focus automatically:</p>
  <input v-focus>
</div>

<script>
// Create root instance
new Vue({
  el: '#app',
  directives: {
    // Register a local custom instruction v-focus
    focus: {
      // Definition of instructions
      inserted: function (el) {
        // Focusing element
        el.focus()
      }
    }
  }
})
</script>

3, hook

1. Hook function

The instruction definition function provides several hook functions (optional):

  • bind: it is only called once. When an instruction is bound to an element for the first time, the hook function can be used to define an initialization action to be executed once during binding.
  • Inserted: called when the bound element is inserted into the parent node (the parent node can be called if it exists, and does not need to exist in the document).
  • Update: called when the template of the bound element is updated, regardless of whether the binding value changes. By comparing the binding values before and after the update, unnecessary template updates can be ignored (see the following for detailed hook function parameters).
  • componentUpdated: called when the template of the bound element completes an update cycle.
  • unbind: only called once, when the instruction and element are unbound.

2. Hook function parameters

The parameters of the hook function are:

  • el: the element bound by the instruction, which can be used to directly operate DOM.

  • binding

    : an object that contains the following properties:

    • Name: instruction name, excluding v-prefix.
    • Value: the binding value of the instruction, for example: v-my-directive = "1 + 1", the value of value is 2.
    • oldValue: the previous value of the instruction binding, only available in the update and componentUpdated hooks. Available regardless of value change.
    • Expression: the expression or variable name of the bound value For example, v-my-directive="1 + 1", the value of expression is "1 + 1".
    • Arg: parameter passed to the instruction. For example, v-my-directive:foo, the value of arg is "foo".
    • Modifiers: an object containing modifiers For example: v-my-directive.foo.bar, the value of modifier object modifiers is {foo: true, bar: true}.
  • Vnode: the virtual node generated by Vue compilation.

  • oldVnode: last virtual node, available only in update and componentUpdated hooks.

<div id="app"  v-runoob:hello.a.b="message">
</div>

<script>
Vue.directive('runoob', {
  bind: function (el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'name: '       + s(binding.name) + '<br>' +
      'value: '      + s(binding.value) + '<br>' +
      'expression: ' + s(binding.expression) + '<br>' +
      'argument: '   + s(binding.arg) + '<br>' +
      'modifiers: '  + s(binding.modifiers) + '<br>' +
      'vnode keys: ' + Object.keys(vnode).join(', ')
  }
})
new Vue({
  el: '#app',
  data: {
    message: 'Rookie tutorial!'
  }
})
</script>

Sometimes we don't need other hook functions. We can abbreviate functions as follows:

Vue.directive('runoob', function (el, binding) {
  // Set the background color of the command
  el.style.backgroundColor = binding.value.color
})
div id="app">
    <div v-runoob="{ color: 'green', text: 'Rookie tutorial!' }"></div>
</div>

<script>
Vue.directive('runoob', function (el, binding) {
	// Setting text and background color in shorthand
	el.innerHTML = binding.value.text
	el.style.backgroundColor = binding.value.color
})
new Vue({
  el: '#app'
})
</script>

IX. Vue.js route

Vue.js routing allows us to access different content through different URL s.

Vue.js can be used to implement a single page web application (SPA) with multiple views.

Vue.js route needs to be loaded Vue router Library

1. Simple example

Vue.js + Vue router can be used in simple single page applications.

< router link > is a component used to set a navigation link and switch different HTML content The to property is the destination address, which is the content to display.

In the following example, we add Vue router, configure components and route mapping, and then tell Vue router where to render them. The code is as follows:

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- Use router-link Components to navigate. -->
    <!-- Pass in `to` Property specifies the link. -->
    <!-- <router-link> By default, it will be rendered as a `<a>` Label -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <!-- Routing exit -->
  <!-- The components to which the route matches will be rendered here -->
  <router-view></router-view>
</div>

<script>
// 0. If you use modularization mechanism to program and import Vue and VueRouter, call Vue.use(VueRouter)

// 1. Define (route) components.
// You can import from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. Define route
// Each route should map a component Where "component" can be
// The component constructor created by Vue.extend(),
// Or, just a component configuration object.
// Let's talk about nested routing later.
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. Create router instance, and then transfer it to 'routes' configuration
// You can also pass other configuration parameters, but it's so simple first.
const router = new VueRouter({
  routes // (abbreviation) equivalent to routes: routes
})

// 4. Create and mount the root instance.
// Remember to inject routes through router configuration parameters,
// So that the whole application has routing function
const app = new Vue({
  router
}).$mount('#app')

// Now, the app has started!
</script>

The style class = "router link exact active router link active" will be added to all clicked navigation links.

2. < router link > related attributes

Next, we can learn more about the properties of < router link >.

1,to

Represents the link to the destination route After being clicked, the value of to will be passed to router.push() immediately, so this value can be a string or an object describing the target location.

<!-- Character string -->
<router-link to="home">Home</router-link>
<!-- Render result -->
<a href="home">Home</a>

<!-- Use v-bind Of JS Expression -->
<router-link v-bind:to="'home'">Home</router-link>

<!-- Not write v-bind Yes, just like binding other properties -->
<router-link :to="'home'">Home</router-link>

<!-- Ditto -->
<router-link :to="{ path: 'home' }">Home</router-link>

<!-- Named route -->
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

<!-- With query parameters, the following results are /register?plan=private -->
<router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>

2,replace

If you set the replace property, when you click, router.replace() will be called instead of router.push(), and no history record will be left after navigation.

<router-link :to="{ path: '/abc'}" replace></router-link>

3,append

After the append property is set, the base path is added before the current (relative) path. For example, we navigate from / A to a relative path B. If append is not configured, then the path is / b. if it is configured, then it is / a/b

<router-link :to="{ path: 'relative/path'}" append></router-link>

4,tag

Sometimes you want < router link > to render as a label, such as < li > So we use the tag prop class to specify which tag, and it will also listen for clicks and trigger navigation.

<router-link to="/foo" tag="li">foo</router-link>
<!-- Render result -->
<li>foo</li>

5,active-class

Sets the CSS class name to use when the link is activated. It can be replaced by the following code.

<style>
   ._active{
      background-color : red;
   }
</style>
<p>
   <router-link v-bind:to = "{ path: '/route1'}" active-class = "_active">Router Link 1</router-link>
   <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link>
</p>

Note that active class is used here.

6,exact-active-class

Configure the class that should be activated when the link is precisely matched. It can be replaced by the following code.

<p>
   <router-link v-bind:to = "{ path: '/route1'}" exact-active-class = "_active">Router Link 1</router-link>
   <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link>
</p>

7,event

Declare events that can be used to trigger navigation. It can be a string or an array of strings.

<router-link v-bind:to = "{ path: '/route1'}" event = "mouseover">Router Link 1</router-link>

The above code sets the event as mouseover, and the HTML content of navigation will change when the mouse moves to Router Link 1.

8. The difference between exact active class and active class

By default, the route of router link is fuzzy matching. For example, if the current path is / article/1, then < router link to = "/ article" > will also be activated. Therefore, after setting the exact active class, this router link will only be activated when the current route is fully inclusive of matching. For example:

<router-link to="/article" active-class="router-active"></router-link>

When the user accesses / article/1, it is activated as:

<a href="#/article" class="router-active" rel="nofollow"></a>

When using:

<router-link to="/article" exact-active-class="router-active"></router-link>

When the user accesses / article/1, the class of this link will not be activated:

<a href="#/article" rel="nofollow"></a>

X. Vue.js Transition & Animation

1, transition

When Vue inserts, updates, or removes DOM, it provides a variety of application transition effects.

Vue provides a built-in transition encapsulation component that wraps the components to achieve the transition effect.

1. Grammar format

<transition name = "nameoftransition">
   <div></div>
</transition>

We can understand how the transition of Vue is achieved through the following examples:

Transition is actually a fade in and fade out effect. Vue provides 6 class es to switch between element display and hidden transition:

  • v-enter: defines the start state of transition. Takes effect before the element is inserted, and is removed at the next frame after the element is inserted.
  • v-enter-active: defines the state when the transition takes effect. Applied throughout the transition phase, effective before the element is inserted and removed after the transition / animation is complete. This class can be used to define the process time, delay and curve function for entering the transition.
  • v-enter-to: 2.1.8 and above definitions enter the end state of transition. The next frame takes effect after the element is inserted (at the same time the v-enter is removed) and after the transition / animation is completed.
  • v-leave: defines the start state of the exit transition. Takes effect immediately when the exit transition is triggered, and the next frame is removed.
  • v-leave-active: defines the state when the leave transition takes effect. Applied throughout the exit transition phase, takes effect immediately when the exit transition is triggered and is removed after the transition / animation is complete. This class can be used to define the process time, delay and curve function of leaving the transition.
  • V-leave-to: the end state of leaving the transition defined in version 2.1.8 and above. The next frame takes effect after the exit transition is triggered (at the same time, v-leave is deleted), and is removed after the transition / animation is completed.

For these class names that are switched in transition, if you use a < transition > without a name, v-is the default prefix for these class names. If you use < transition name = "my transition" >.

2. Use transition and animation at the same time

In order to know the completion of the transition, Vue must set up the corresponding event listener. It can be transitionend or animationend, depending on the CSS rules applied to the element. If you use any of these, Vue can automatically recognize the type and set up listening.

However, in some scenarios, you need to set two transition effects for the same element at the same time. For example, animation will be triggered and completed soon, but the transition effect is not over yet. In this case, you need to use the type attribute and set animation or transition to explicitly declare the type you want Vue to listen to.

3. Dominant transition duration

In many cases, Vue can automatically arrive at the completion time of the transition effect. By default, Vue waits for its first transitionend or animationend event on the root element of the transition effect. However, it can also be set differently - for example, we can have a carefully choreographed set of transition effects in which some nested internal elements have a delayed or longer transition effect than the root element of the transition effect.

In this case, you can use the duration attribute on the < transition > component to customize an explicit transition duration (in milliseconds):

<transition :duration="1000">...</transition>

You can also customize the duration of entry and removal:

<transition :duration="{ enter: 500, leave: 800 }">...</transition>

4,transition-group

Vue.js 2.0 provides the transition group label, which is convenient to work on multiple DOM. The main function of transition group is to set a uniform transition style for its sub elements. The transition group is a virtual label, and the transition group will actually render in the DOM. You can set it through the tag attribute. Each transition group sub element needs to contain a unique key.

<transition-group tag="ul" name="fade">
	<li v-for="item in items" :key="item.id">
	{{item.text}}
	</li>
</transition-group>

Xi. Vue.js mixed in

**Mixins define some reusable methods or computing properties. **A blend object can contain any component option. When a component uses a mixed object, all the options of the mixed object are mixed into the options of the component itself.

<script>
	var mixin={
		created:function(){
			document.writeln('Call in'+'<br>')
		}
	}
	new Vue({
		 mixins:[mixin],
		created:function(){
			document.writeln('Component invocation'+'<br>');
		}
	});

1. Global blending

You can also register mixed objects globally. Pay attention to use Once a global blend object is used, all subsequent Vue instances are affected. When used properly, you can inject processing logic into custom objects.

<script type = "text/javascript">
// Inject a processor for the custom option 'myOption'.
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      document.write(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})
// => "hello!"
</script>

Use global blending objects with caution, as it affects each individually created instance of Vue, including third-party templates.

XII. Data transfer between components

1. Parent child component

1. Define another component within one component, which is called parent-child component

2. The child component can only be used inside the parent component

3. By default, the child component cannot access the data in the parent component, and the scope of each component instance is independent

<div id="itany">
			<my-hello></my-hello>
			<!--my-word yes my-hello The child component of cannot be used in the root element and cannot be leveled with the parent element-->
			<!--<my-word></my-word>-->
		</div>
		
		<template id="hello">
			<div>
				<h2>I am the parent component</h2>
				<h2>My name is:{{name}}</h2>
				<h3>Age:{{age}}</h3>
				<p>I like it{{msg}}</p>
				<hr />
				<!--my-word yes my-hello Can only be used in my-hello Use in-->
				<my-word></my-word>
			</div>

		</template>
		
		<template id="word">
			<h3>I am a subcomponent</h3>
			<!--The data of the parent component cannot be accessed directly by the child component. The data between components is independent-->
			<!--<h4>I want to access the data of the parent component:{{name}},{{age}},{{msg}}</h4>-->
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				components:{
					'my-hello':{
						template:'#hello',
						data(){
							return {
								msg:'vue.js',
								name:'sun',
								age:25
							}
						},
						components:{
							'my-word':{
								template:'#word'
							}
						}
					}
				}
			});
		</script>

2. Data communication between components

1. The child component accesses the data of the parent component

1. Bind the data to be obtained from the parent component in the child component

2. In the sub component, use props to display the data obtained by declaration

Note: the parent component passes data down through props

<div id="itany">
			<my-hello></my-hello>
			<!--my-word yes my-hello The child component of cannot be used in the root element and cannot be leveled with the parent element-->
			<!--<my-word></my-word>-->
		</div>
		
		<template id="hello">
			<div>
				<h2>I am the parent component</h2>
				<h2>My name is:{{name}}</h2>
				<h3>Age:{{age}}</h3>
				<p>I like it{{msg}}</p>
				<hr />
				<!--my-word yes my-hello Can only be used in my-hello Use in-->
				<!--Binding a property (custom) to pass the data of the parent component to the child component-->
				<my-word :message="msg"></my-word>
			</div>

		</template>
		
		<template id="word">
			<div>
				<h3>I am a subcomponent</h3>
				<!--The data of the parent component cannot be accessed directly by the child component. The data between components is independent-->
				<!--<h4>I want to access the data of the parent component:{{name}},{{age}},{{msg}}</h4>-->
				<h4>Use props Data obtained from the parent component after the data binding declaration:{{message}}</h4>
			</div>
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				components:{
					'my-hello':{
						template:'#hello',
						data(){
							return {
								msg:'vue.js',
								name:'sun',
								age:25
							}
						},
						components:{
							'my-word':{
								template:'#word',
								props:['message']
							}
						}
					}
				}
			});
		</script>
components:{
							'my-word':{
								template:'#word',
								/*props:['message']*/
								/*props It can also be an object, allowing configuration of advanced settings, such as type judgment, data verification, and setting default values*/
								props:{
									message:String,
									name:{
										type:String,
										required:true
									},
									age:{
										type:Number,
										default:18,
										validator:function(val){
											return val>=0
										}
									}
								}
							}
						}

2. The parent component accesses the data of the child component

1. Use VM. $emit (event name, data) in the subcomponent to trigger a custom event (event name customization)

2. The parent component listens for events triggered by the child component where the child component is used, and defines methods in the parent component to receive data

Note: the child component passes information to the parent component through the events event

<div id="itany">
			<my-hello></my-hello>
			<!--my-word yes my-hello The child component of cannot be used in the root element and cannot be leveled with the parent element-->
			<!--<my-word></my-word>-->
		</div>
		
		<template id="hello">
			<div>
				<h2>I am the parent component</h2>
				<h2>My name is:{{name}}</h2>
				<h3>Age:{{age}}</h3>
				<h3>I like it{{msg}}</h3>
				<h3>To access data for a subcomponent:{{sex}},{{height}}</h3>
				<hr />
				<!--my-word yes my-hello Can only be used in my-hello Use in-->
				<!--Binding a property (custom) to pass the data of the parent component to the child component-->
				<my-word :message="msg" :name="name" :age="age" @e-word="getData"></my-word>
			</div>

		</template>
		
		<template id="word">
			<div>
				<h3>I am a subcomponent</h3>
				<!--The data of the parent component cannot be accessed directly by the child component. The data between components is independent-->
				<!--<h4>I want to access the data of the parent component:{{name}},{{age}},{{msg}}</h4>-->
				<h4>Use props Data obtained from the parent component after the data binding declaration:{{message}},{{name}},{{age}}</h4>
				<h4>Subcomponents access their own data:{{sex}},{{height}}</h4>
				<button @click="send">Send data from child component up to parent component</button>
			</div>
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				components:{
					'my-hello':{
						template:'#hello',
						data(){
							return {
								msg:'vue.js',
								name:'sum',
								age:25,
								sex:'',
								height:''
							}
						},
						methods:{
							getData(sex,height){
								this.sex=sex;
								this.height=height;
							}
						},
						components:{
							'my-word':{
								data(){
									return {
										sex:'male',
										height:167
									}
								},
								template:'#word',
								/*props:['message']*/
								/*props It can also be an object, allowing configuration of advanced settings, such as type judgment, data verification, and setting default values*/
								props:{
									message:String,
									name:{
										type:String,
										required:true
									},
									age:{
										type:Number,
										default:18,
										validator:function(val){
											return val>=0
										}
									}
								},
								methods:{
									send(){
										/*At this time, this value is the context of the current file, i.e. my word*/
										this.$emit('e-word',this.sex,this.height);
									}
								}
							}
						}
					}
				}
			});
		</script>

3. One way data flow

1 * * and props are one-way binding. When the data of the parent component changes, they will be passed to the child component, but the child component will not be passed to the parent component**

2. The data in the parent component cannot be modified directly by the child component

3. Solutions:

3.1 if the fruit component wants to use the data obtained from the parent component as the local data, it can store the data obtained from the parent component into another variable. At this time, the data in the parent component will not be affected

<div id="itany">
			<h3>Parent component:{{name}}</h3>
			<input type="text" v-model="name"/><br />
			<my-hello :name="name"></my-hello>
		</div>
		
		<template id="hello">
			<div>
				<h3>Sub components:{{username}}</h3>
				<button @click="change">Modifying data</button>
			</div>
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				data:{
					name:'tom'
				},
				components:{
					'my-hello':{
						template:'#hello',
						props:['name'],
						data(){
							return {
								username:this.name
							}
						},
						methods:{
							change(){
								this.username='alice'
							}
						}
						
					}
				}
			});
		</script>

3.2 if the child component wants to modify the data and synchronously update it to the parent component, there are two implementation methods

Method 1: use the. sync modifier (vue2.3 +)

<div id="itany">
			<h3>Parent component:{{name}}</h3>
			<input type="text" v-model="name"/><br />
			<my-hello :name.sync="name"></my-hello>
		</div>
		
		<template id="hello">
			<div>
				<h3>Sub components:{{name}}</h3>
				<button @click="change">Modifying data</button>
			</div>
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				data:{
					name:'tom'
				},
				components:{
					'my-hello':{
						template:'#hello',
						props:['name'],
						/*data(){
							return {
								username:this.name
							}
						},*/
						methods:{
							change(){
								/*
								this.name='alice'
								Cannot be modified directly, event method must be used
								update It must be added
								*/
								this.$emit('update:name','alice');
							}
						}
						
					}
				}
			});
		</script>

Method 2: wrap the data of the parent component into an object, and then modify the properties of the object in the child component

<div id="itany">
			<h3>Parent component:{{name}}</h3>
			<h3>Parent component:{{user.age}}</h3>
			<input type="text" v-model="name"/><br />
			<my-hello :name.sync="name" :user="user"></my-hello>
		</div>
		
		<template id="hello">
			<div>
				<h3>Sub components:{{name}}</h3>
				<h3>Sub components:{{user.age}}</h3>
				<button @click="change">Modifying data</button>
			</div>
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				data:{
					name:'tom',
					user:{
						name:'bead',
						age:20
					}
				},
				components:{
					'my-hello':{
						template:'#hello',
						props:['name','user'],
						/*data(){
							return {
								username:this.name
							}
						},*/
						methods:{
							change(){
								/*
								this.name='alice'
								Cannot be modified directly, event method must be used
								update It must be added
								*/
//								this.$emit('update:name','alice');
								/*The storage space of the object user has not changed, only the property value has been modified, so the property value of the object has been modified in the subcomponent,
								 Causes the property value of the parent component to change (both parent and child components are instance references to the same object)*/
								this.user.age=18;
							}
						}
						
					}
				}
			});
		</script>

4. Communication between non parent and child components

The communication between non parent and child components can be used as the central control bus through an empty Vue instance

var bus=new Vue();

Bus. $emit (event name, data);

Bus. $on (event name, callback (data to be monitored));

Note: it is better to use arrow function for listening callback function. This of arrow function points to the object containing this function, while this of ordinary function points to the empty Vue instance calling this event listening.

<div id="itany">
			<my-a></my-a>
			<my-b></my-b>
			<my-c></my-c>
		</div>
		
		<template id="a">
			<div>
				<button @click="send">Transfer data to C</button>
				<h3>A Components:{{name}}</h3>
			</div>
		</template>
		<template id="b">
			<div>
				<h3>B Components:{{age}}</h3>
			</div>
		</template>
		<template id="c">
			<div>
				<h3>C Components:{{name}}</h3>
			</div>
		</template>
		
		<script>
			/*Create an empty Vue instance as the control bus,
			 As a transit station for communication between non parent and child components*/
			var bus=new Vue();
			var A={
				template:'#a',
				data(){
					return {
						name:'tom'
					}
				},
				methods:{
					send(){
						/*Sending events*/
						bus.$emit('data-a',this.name);
					}
				}
			}
			var B={
				template:'#b',
				data(){
					return {
						age:20
					}
				}
			}
			var C={
				template:'#c',
				data(){
					return {
						name:'',
						age:''
					}
				},
				mounted(){
					/*Monitoring events*/
					bus.$on('data-a',name=>{
						this.name=name;
					});
				}
			}
			new Vue({
				el:'#itany',
				components:{
					'my-a':A,
					'my-b':B,
					'my-c':C
				}
			});
		</script>

XIII. slot content distribution

<div id="itany">
			<!--The content between custom components is replaced by the content in the template. If you want to display the
				Content, should use slot Label
			-->
			<my-hello>hello word</my-hello>
		</div>
		
		<template id="hello">
			<div>
				<h3>welcome to itany</h3>
				<!--Use slot Tag to get content contained between custom components-->
				<slot></slot>
			</div>
		</template>
		
		<script>
			new Vue({
				el:'#itany',
				components:{
					'my-hello':{
						template:'#hello'
					}
				}
			});
		</script>

XIV. Vue router

1. Basic usage

<div id="itany">
			<!--Use router-link To define navigation, properties to To define links-->
			<div>
				<!--router-link It will eventually render to a Label, to then is href-->
				<router-link to="/home">homepage</router-link>
				<router-link to="/news">Journalism</router-link>
			</div>
			<!--router-view Is the route exit, matching the contents of the route, matching components
				//Render here
			-->
			<router-view></router-view>
			
		</div>
		
		
		<script>
			/* Create route instance*/
			const router=new VueRouter({
				/*Configure routing and component creation*/
				routes:[
					{path:'/home',component:{
						template:'<h3>I am the home page.</h3>'
					}},
					{path:'/news',component:{
						template:'<h3>I am news.</h3>'
					}}
				]
			});
			new Vue({
				el:'#itany',
				router:router  //Route injection using router
			});
		</script>

2. Route nesting and parameter transfer

1. Routing nesting

<div id="app">
			<div>
				<router-link to="/home">homepage</router-link>
				<router-link to="user">user</router-link>
			</div>
			<router-view></router-view>
		</div>
		
		<template id="user">
			<div>
				<h3>I am the user.</h3>
				<ul>
				<li><router-link to="/user/login">User login</router-link></li>
				<li><router-link to="/user/regist">User registration</router-link></li>
			</ul>
			<router-view></router-view>
			</div>
		</template>
		
		<script>
			const Login={
				template:'<h4>User login....</h4>'
			}
			const Regist={
				template:'<h4>User registration....</h4>'
			}
			const User={
				template:'#user'
			}
			const router=new VueRouter({
				routes:[
					{path:'/home',component:{
						template:'<h3>I am the home page.</h3>'
						}
					},
					{path:'/user',component:User,
						children:[
							{path:'login',component:Login},
							{path:'regist',component:Regist}
						]
					}
				]
			});
			new Vue({
				el:'#app',
				router:router
			});
		</script>

2. Parameter transfer

There are two ways to pass parameters:

a: query string: login? Name = Alice & PSW = 456

{{$route.query}}

b:rest style URL: register /: name /: password

{{$route.params}}

<div id="app">
			<div>
				<router-link to="/home">homepage</router-link>
				<router-link to="user">user</router-link>
			</div>
			<router-view></router-view>
		</div>
		
		<template id="user">
			<div>
				<h3>I am the user.</h3>
				<ul>
				<li><router-link to="/user/login?name=alice&psw=456">User login</router-link></li>
				<li><router-link to="/user/regist/tom/678">User registration</router-link></li>
			</ul>
			<router-view></router-view>
			</div>
		</template>
		
		<script>
			const Login={
				template:'<h4>User login.... Login data:{{$route.query}}</h4>'
			}
			const Regist={
				template:'<h4>User registration.... Registration data:{{$route.params}}</h4>'
			}
			const User={
				template:'#user'
			}
			const router=new VueRouter({
				routes:rount=[
					{path:'/home',component:{
						template:'<h3>I am the home page.</h3>'
						}
					},
					{path:'/user',component:User,
						children:[
							{path:'login',component:Login},
							{path:'regist/:name/:password',component:Regist}
						]
					}
				]
			});
			new Vue({
				el:'#app',
				router:router
			});
		</script>

15. Single file component (. vue file)

1. A. vue file is a separate component. The file consists of three parts: template, style and script

2. The browser does not know the. vue file itself, so it must load and parse the. vue file. At this time, it needs to use the vue loader

The project directory file created with webpack is as follows:

​ |-index.html

| - main.js -- entry file

| - App.vue - Vue file

| - package.json -- project file (npm init --yes)

| - webpack.config.js -- webpack configuration file

Load resolution tool to be configured: cnpm install - D webpack webpack dev server Vue loader Vue HTML loader CSS loader Vue style loader file loader Babel loader Babel core Babel preset env Vue template compiler

Cnpm install vue-s (production mode, import in project)

XVI. Manual construction of project module

1. App.vue file

<template>
	<div id="itany">
		<h1>welcome to itany</h1>
		<p>{{name}}</p>
		<user></user>
	</div>
</template>

<script>
	//Import another component
	import User from './components/user.vue'
	
	export default {
		data(){
			return {
				name:'tom'
			}
		},
		components:{
			User
		}
	}
</script>

<style>
	body{
		background-color:#ccc;
	}
</style>

//Another component, User.vue
<template>
	<div class="user">
		<h2>User list</h2>
		<ul>
			<li v-for="value in users">{{value}}</li>
		</ul>
	</div>
</template>

<script>
	export default {
		data(){
			return {
				users:['tom','jack','alice']
			}
		}
	}
</script>

<style>
	.user h2{
		color:red;
	}
</style>

2. main.js file

/*
 Using es6 syntax to introduce templates
 * */
import Vue from 'vue'
import App from './App.vue'

new Vue({
	el:'#app',
	render:function(h){//Rendering components using the render function
		return h(App);
	}
});

3. webpack.config.js file

model.exports={
	//Configure portal file
	entry:'./main.js',
	//Configure portal file output location
	output:{
		path:__dirname,//The root path of the project
		filename:'build.js'
	},
	//Configure module loader
	module:{
		rules:[
			{	text:/\.vue$/,//All files ending in. vue are loaded in vue loader
				loader:'vue-loader'
			},
			{
				text:/\.js$/,
				loader:'babel-loader',//All files ending with. js are loaded with Babel loader, except node_modules
				exclude:/node_modules/
			}
		]
	}
}

4. package.json file

{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --open --hot --port 8800"//Just change this one, and the rest don't change
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "css-loader": "^3.2.0",
    "file-loader": "^4.2.0",
    "vue-html-loader": "^1.2.4",
    "vue-loader": "^15.7.1",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.40.2",
    "webpack-cli": "^3.3.8",
    "webpack-dev-server": "^3.8.0"
  }
}

5. index.html file

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="build.js"></script>
		<title></title>
	</head>
	<body>
		<div id="app"></div>
	</body>
</html>

6. babelrc file

{
	"presets":[
		["env",{"model":false}]
	]
}

XVII. Vue cli scaffold

1. Introduction to Vue cli

vue cli is a project scaffold of vue, which integrates various project templates, such as webpack (including ESLint, etc.), webpack simple

Installation: NPM install - G @ Vue / cli init

Create project syntax: vue init template project name

Installation dependency file: npm install

Run test: npm run dev

Go online: npm run build / / package the project and output the dist directory. To go online, you need to copy the dist to the server

2. Modular development

1. Installation route: cnpm install Vue router-s (production dependent)

2. Edit main.js, import Vue router module (import Vue router from 'Vue router') and use (Vue. Use (Vue router);)

3, list

1,App.vue

<template>
  <div id="app">
    <h1>{{ msg }}</h1>
    <h3>
    	<router-link to="/home">home page</router-link>
    	<router-link to="/news">Journalism</router-link>
    </h3>
    <div>
    	<keep-alive>
    		<router-view></router-view>
    	</keep-alive>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to itany'
    }
  }
}
</script>

2,Home.vue

<template>
	<div id="home">
		<h3>This is the homepage.</h3>
	</div>
</template>


3,News.vue

<template>
	<div id="news">
		<h3>This is news.</h3>
	</div>
</template>


4,router.config.js

import Home from './components/Home.vue'
import News from './components/News.vue'

export default {
	routes:[
		{path:'/home',component:Home},
		{path:'/news',component:News}
	]
}

5,main.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import RouterConfig from './router.config.js'

//Using VueRouter
Vue.use(VueRouter);

//Create route instance
const router=new VueRouter(RouterConfig);

new Vue({
  el: '#app',
  render: h => h(App),
  router
})

4. Use of axios in module development

Download: cnpm install axios -S

Method 1: import axios from 'axios' in every file using ajax

Method 2: introduce axios globally in main.js and add it to the prototype of Vue

​ import axios from 'axios'

​ Vue.prototype.$ajax=axios

Note: Vue.use() cannot be used to add

//main.js
Vue.prototype.$http=axios;//After introducing axios globally, it is added to the Vue prototype (cannot be added using Vue.use), $ajax can customize the name, such as $http, etc

//App.vue
methods:{
  	send(){
  		this.$http.get('https://api.github.com/users/')
  		.then(resp=>{
  			console.log(resp.data);
  		}).catch(err=>{
  			console.log(resp.err);
  		});

5. Add events for custom components

Custom component cannot bind Vue event by default, use v-on modifier. Native (listen to native component)

//MyButton.vue
<template>
	<button>custom button</button>
</template>

<style scoped>
	button{
		width:100px;
		height:30px;
		background-color:#ccc;
		color:red;
	}
</style>

//App.vue
<MyButton @click.native="send"></MyButton>//Add. native modifier for custom component listening events

import MyButton from './components/MyButton.vue'

XVIII. Element UI

1, introduction

Is the Element UI hungry? The component library based on Vue2.0 + provided by the team can quickly build websites

Element UI PC

Min UI mobile terminal

[http://element.eleme.io]

Download: cnpm install element UI - S (production dependent)

Introduced in main.js,

import ElementUI from 'element-ui' 
import 'element-ui/lib/theme-chalk/index.css' //CSS styles need to be introduced separately

Vue.use(ElementUI); //Use

In this way, all components of the ElementUI are introduced, and the configuration of webpack.config.js may need to be changed. The actual situation depends on the version of ElementUI. Currently, the latest version has files of woff and ttf, which need to be added

{
        test: /\.(png|jpg|gif|svg|woff|ttf)$/, 	//Add woff, ttf
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }

There is no style loader or Vue style loader in webpack.config.js by default, which may need to be installed. The latest default already has CSS loader, so CSS loader does not need to be configured

{
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'style-loader',
          'css-loader' 	//CSS loader must be placed in the last configuration, otherwise it may report an error
        ],

2. Customize global components (plug-ins)

To customize a global component, you need to provide an install method, then import the file in main.js, and call it with Vue.use() (in the form of a plug-in)

//index.js

import Login from './Login.vue'

export default {
    install:function(vue){
        vue.component('Login',Login);
    }
}
//Login.vue
<template>
	<div id="login">
		<h2>{{msg}}</h2>
	</div>
</template>

<script>
	export default {
		data(){
			return {
				msg:'What am I doing? Why am I here?'
			}
		}
	}
</script>

<style>
	#login h2{
		color:red;
		text-shadow:2px 2px 5px #550;
	}
</style>
//main.js

import Login from './components/user/index.js'

Vue.use(Login);

XIX. Vuex

1, introduction

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and ensures that the state changes in a predictable way with corresponding rules.

Simply speaking, it's used to manage data. The front-end state management framework based on flux

Note: if you do not plan to develop large single page applications, using Vuex can be cumbersome and redundant. That's true - if your application is simple enough, you'd better not use Vuex.

2. Basic usage

Installation: cnpm install vuex - S (production dependent)

Tags: Front-end Vue Webpack axios Attribute

Posted on Mon, 04 Nov 2019 17:05:12 -0800 by DrDre