Continue the previous article: Vue.js 2.0 Quick start Essence Combing

1. Description and use of VUE components

A component is essentially a Vue instance with predefined options inside the header component for external use, requiring exported properties, which can be exported in two ways

  1. Default export (unnamed)
    export default {
    data () {
    return {
    msg: 'header'}}}Copy the code

    The above code actually generates a new VUE automatically

Import in the parent component

import Header from './components/header'Copy the code

2. Add a keyword directly before any variable or function

exportconst sqrt = Math.sqrt; Import import SQRT from in the parent component'./components/header'; Reference a component import Header from'./components/header'Copy the code

Defined in this component

export default{
 data: function() {}, //data must return a function components: {comHeader: Header // declare component}}Copy the code

Used in template

<template>
 <div class="com-app">< com-header></com-header> // Note that HTML is case insensitive, so you need to write comHeader as com-header </div> </template>Copy the code

A VUE object usually contains the following attributes

Data: // Data of the VUE object methods: // Methods of the VUE object watch: // Methods of the object listening computed: // Calculation logic put in computed created: // The property is bound, but the DOM is not generated. Ajax processing and page initialization are usually done hereCopy the code

2. vuex


Some global information, such as rendering of header content, whether to display, when to display loading, when to hide, and the fixed value of the interface API, are written in the state of the Store record component.

const store = new Vuex.Store({
 state: {
 comm: {
  loading: false// Whether to loading apiUrl:'http://www.sherlochao.com:9091/photosharing/', // interface base URL imgUrl:'http://www.sherlochao.com:9091/filebase'Base url indexConf: {isFooter:true// Whether to display the bottom isSearch:true// Whether to display search isBack:false// Whether to display isShare:false// Whether to display the shared title:' '// Title}}}})Copy the code

Change the state on mutations

Open open = new vuex. open ({mutations: {// open open) (state, status) => {state.com m.log = status}, // Modify header information changeIndexConf: (state, data) => {object.assign (state.m.I. NdexConf, data)}}) LLDB Specifies whether to display LLDB information in header.vueexport default {
 data: function () {
  return {}
 },
 computed: {
  isShowSearch: function () {
  return this.$storeState.com m.i ndexConf. IsSearch / / get vuex inside the state status value}, title:function () {
  return this.$store.state.comm.indexConf.title
  },
  isBack: function () {
  return this.$store.state.comm.indexConf.isBack
  }
 }
}Copy the code

The template code

<template>
 <div class="header">
 <div v-show="isShowSearch"></div>
 <div class="title" v-show=! "" isShowSearch">
  <a v-show="isBack" class="back t-icon" @click="goBack"><span
  class="iconfont icon icon-xiangzuojiantou"></span></a>
  <p>{{title}}</p>
 </div>
 </div>
</template>Copy the code

Control whether the header is displayed elsewhere, where LLDB: details page

export default { 
 created: function () {
  vm.$store.commit('changeIndexConf', {
  isFooter: false,
  isSearch: false,
  isBack: true,
  isShare: true,
  title: 'Details Page'}}})Copy the code

3. Summary of development practice

  1. vue-router

Since the entire project list component is common in many places, and ‘my favorites’,’ search results page ‘, ‘My circle’, and just from /search/own to /search/star, the original component instance will be reused, meaning that the component’s lifecycle hook will no longer be invoked: When reusing a component, you can simply watch an object to respond to changes in routing parameters

export default {
 watch: {
 '$route'(to, from) {// Respond to routing changes... }}}Copy the code

2. Determine whether to log in

When entering the personal information page, the router will intercept the information to determine whether you have logged in. The specific code is as follows

router.beforeEach(function (to,from,next) {
 var userMsg = localStorage.getItem('userMsg')
 if(to.path === '/home') {if(! userMsg){ next({ path:'/login' })
 }
 }
 next()
})Copy the code

3. Commonly used API

1). Click the event to get the current object

2). Get the current DOM object like jquery

<input type="submit" disabled="canSubmit" ref="isSubmit" @click="register" value="Register now" class="button"/>

 this.$refs.isSubmit.removeAttribute('disabled'// Use this.$refsGet the current DOMCopy the code

From github.com/beidan/phot…

Consideration of the need to reuse components

If a component needs to be used more than once, think about the interface from the beginning, and don’t think about extending the interface after you’ve already used many components. In general, the interface of a Vue component consists of three aspects:

Props (data) allows outsiders to pass data to components; Events allow Events within a component to be propagated outward; Slots (Slots) allows external editing of HTML content within components;

<my-component
  :foo="baz"
  :bar="qux"
  @event-a="doThis"
  @event-b="doThat"
>
  <img slot="icon" src="...">
  <p slot="main-text">Hello! </p> </my-component>Copy the code

These are the three interfaces used in component calls; Note the short versions of v-bind and V-on, which help make your code look cleaner;

Gets an instance of a component

It is easy to get an instance of a Vue, such as VM; But getting an instance of a component is not easy because it is a template that is used many times; Each use is an instance; Most of the time we change the internal data of the component by passing parameters, but sometimes we need to get the instance directly and change the data of the instance; It can go like this:

<div id="parent">
  <user-profile ref="profile"></user-profile>
</div>Copy the code

Ref =”profile” gives a component an ID, so we can get an instance of the component like this:

var vm = new Vue({ el: '#parent' })
// access child component instance
var child = vm.$refs.profileCopy the code

What is the use of obtaining this instance? You can change the data in the component directly. See this example: jsfiddle.net/woodytang/8…

Asynchronous components

A component is either in the DOM or not, and for some large apps, there will be many components at once, and you may need to decide how to load them based on certain conditions rather than loading them all at once;

When we define a component, we can take two callback functions as parameters:

Vue.component('async-example'.function (resolve, reject) {
  setTimeout(function () {
    resolve({
      template: '
      
I am async!
'
}})}, 1000))Copy the code

Resolve and reject mean that when a condition is met, I can render the component or reject it;

The setTimeout in the above example is just a demonstration, so you can define your own conditions.

Naming conventions for components

When you define it

// in a component definition
components: {
  // register using camelCase
  'kebab-cased-component': {/ *... * /},'camelCasedComponent': {/ *... * /},'TitleCasedComponent': {/ *... * /}}Copy the code

In Html, because Html is case sensitive, so:

<! -- alway use kebab-casein HTML templates -->
<kebab-cased-component></kebab-cased-component>
<camel-cased-component></camel-cased-component>
<title-cased-component></title-cased-component>Copy the code

They all look the same; In the String template:

<! -- use whatever you wantin string templates! -->
<my-component></my-component>
<myComponent></myComponent>
<MyComponent></MyComponent>Copy the code

Optional;

Recursive components

Sometimes, you need a nested view of recursive calls;

name: 'stack-overflow',
template: '<div><stack-overflow></stack-overflow></div>'Copy the code

First you have to have a name attribute; Second, the above code will report an infinite loop error because it nested itself without adding conditions. Such as v-if, can stop the loop if necessary.

Templates written inside component tags

We usually define the template of the component inside the component; But you could also write:

<my-component inline-template>
  <p>These are compiled as the component's own template.

Not parent'

s transclusion content.</p> </my-component>Copy the code

Add an inline-template so that the contents inside the my-Component tag will not replace the slot inside the component, but will be rendered as the my-Component template. This is not really useful except for confusion.

x-template

For htML-heavy templates, you can define the template outside:

<script type="text/x-template" id="hello-world-template">
  <p>Hello hello hello</p>
</script>
Vue.component('hello-world', {
  template: '#hello-world-template'
})Copy the code

Static components

For components that don’t require data binding at all, you can use V-once inside the template to generate caching and save a lot of performance.

Vue.component('terms-of-service', {
  template: '\ 
      
\

Terms of Service

\ ... a lot of static content ... \
\ '
})Copy the code

Learn more about VUe2.0

Vue2.0 using dynamic components to achieve Tab Tab switching effect (VUE-CLI) Vue2.0 development introductory notes. Vue file generation and use Vuejs2.0 document overview vue2.0 permission tree component implementation code Vuejs2.0 implements the paging component’s way of using $emit for event listening data delivery