vue components, routing, event

Vue defined components

Component Definition

Has a component, is to split the amount of code Vue instance, and allow us to different components, divided into different functional modules to the future what kind of functions we need, you can call the corresponding components can go;

And a modular assembly of different

  • Modular: the code is divided from the logical point of view; single-layer code to facilitate the development and ensure the functions of each functional module;
  • Components of: angle is divided from the UI interface; front-end components for easy reuse UI components;

    Global components defined in three ways

  1. Use Vue.extend with Vue.component method:
var login = Vue.extend({
      template: '<h1>登录</h1>'
    });
Vue.component('login', login);
  1. Directly Vue.component method:
Vue.component('register', {
    template: '<h1>注册</h1>'
});
  1. The template string, to define the script tag types:
<script id="tmpl" type="x-template">
      <div><a href="#">登录</a> | <a href="#">注册</a></div>
</script>
//同时,需要使用 Vue.component 来定义组件
Vue.component('account', {
    template: '#tmpl'
});

Note: DOM structure assembly, there is a unique one and only root element (Root Element) to wrap!

Components and display data in response to events

  1. In assembly, datait needs to be defined as a method, for example:
Vue.component('account', {
  template: '#tmpl',
  data() {
    return {
      msg: '大家好!'
    }
  },
  methods:{
    login(){
      alert('点击了登录按钮');
    }
  }
});
  1. In sub-assembly, if the template string, to define the script tag, then, to access the body of the sub-assemblies datavalue of the property, you need to use thisto access;

Use componentsattribute defines a partial subassembly

  1. Examples of the component is defined by:
<script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {},
      components: { // 定义子组件
        account: { // account 组件
          template: '<div><h1>这是Account组件{{name}}</h1><login></login></div>', // 在这里使用定义的子组件
          components: { // 定义子组件的子组件
            login: { // login 组件
              template: "<h3>这是登录组件</h3>"
            }
          }
        }
      }
    });
</script>
  1. Reference components:
<div id="app">
    <account></account>
</div>

Switch components

Use flagthe identifier in combination v-ifand v-elseswitching component

  1. Page structure:
<div id="app">
    <input type="button" value="toggle" @click="flag=!flag">
    <my-com1 v-if="flag"></my-com1>
    <my-com2 v-else="flag"></my-com2>
</div>
  1. Vue instance definition:
<script>
    Vue.component('myCom1', {
      template: '<h3>奔波霸</h3>'
    })

    Vue.component('myCom2', {
      template: '<h3>霸波奔</h3>'
    })

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        flag: true
      },
      methods: {}
    });
</script>

Use :isproperty to switch between different sub-components, and adding animation switching

  1. Examples of the component is defined manner
// 登录组件
const login = Vue.extend({
  template: `<div>
    <h3>登录组件</h3>
  </div>`
});
Vue.component('login', login);

// 注册组件
const register = Vue.extend({
  template: `<div>
    <h3>注册组件</h3>
  </div>`
});
Vue.component('register', register);

// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
  el: '#app',
  data: { comName: 'login' },
  methods: {}
});
  1. Use componentlabels to refer to a component by :isspecify the component to be loaded properties:
<div id="app">
    <a href="#" @click.prevent="comName='login'">登录</a>
    <a href="#" @click.prevent="comName='register'">注册</a>
    <hr>
    <transition mode="out-in">
      <component :is="comName"></component>
    </transition>
</div>
  1. Adding to switch styles:
<style>
    .v-enter, .v-leave-to {
      opacity: 0;
      transform: translateX(30px);
    }

    .v-enter-active, .v-leave-active {
      position: absolute;
      transition: all 0.3s ease;
    }

    h3{
      margin: 0;
    }
</style>

Sons components by value

Parent component subassembly to pass values

  1. Component instance defined method, NOTE: Be sure to use the propsproperty to define the data transfer from the parent component
<!--子组件-->
<script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        msg: '这是父组件中的消息'
      },
      components: {
        son: {
          template: '<h1>这是子组件 --- {{finfo}}</h1>',
          props: ['finfo']
        }
      }
    });
</script>
  1. Use v-bindor simplified instruction, passes the data to the sub-assembly:
<!--父组件-->
<div id="app">
    <son :finfo="msg"></son>
</div>

Value transmitted to the parent sub-assembly components

  1. Principle: The parent component of the reference method, the method passed to the internal sub-assemblies, subassemblies, call the parent component inside pass over, while the data to be sent to the parent component, as a parameter passed in when calling the method;
  2. Parent component references passed to the method sub-assembly, which getMsgis the parent component of the methodsmethod name defined in the funcmethod sub-assembly method when passing over the name calling
<son @func="getMsg"></son>
  1. Interior subassembly by this.$emit('方法名', 要传递的数据)way to call methods parent components, while the components used to pass data to the parent
<div id="app">
    <!-- 引用子组件 -->
    <son @func="getMsg"></son>

    <!-- 组件模板定义 -->
    <script type="x-template" id="son">
      <div>
        <input type="button" value="向父组件传值" @click="sendMsg" />
      </div>
    </script>
</div>

<script>
    // 子组件的定义方式
    Vue.component('son', {
      template: '#son', // 组件模板Id
      methods: {
        sendMsg() { // 按钮的点击事件
          this.$emit('func', 'OK'); // 调用父组件传递过来的方法,同时把数据传递出去
        }
      }
    });

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getMsg(val){ // 子组件中,通过 this.$emit() 实际调用的方法,在此进行定义
          alert(val);
        }
      }
    });
</script>

Use this.$refsto get the elements and components

<div id="app">
    <div>
      <input type="button" value="获取元素内容" @click="getElement" />
      <!-- 使用 ref 获取元素 -->
      <h1 ref="myh1">这是一个大大的H1</h1>

      <hr>
      <!-- 使用 ref 获取子组件 -->
      <my-com ref="mycom"></my-com>
    </div>
</div>

<script>
    Vue.component('my-com', {
      template: '<h5>这是一个子组件</h5>',
      data() {
        return {
          name: '子组件'
        }
      }
    });

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getElement() {
          // 通过 this.$refs 来获取元素
          console.log(this.$refs.myh1.innerText);
          // 通过 this.$refs 来获取组件
          console.log(this.$refs.mycom.name);
        }
      }
    });
</script>

routing

What is routing

  1. For the average website, all hyperlinks are URL addresses, URL addresses corresponding to all of the resources corresponding to the server;

  2. For single-page applications, mainly realized by switching between different pages in the URL hash (# number), while, a hash features: HTTP request does not contain relevant content hash; therefore, a single page of the application the main page jump implemented hash;

  3. In the single-page applications in this manner to switch the page by changing the hash, called the front end of the route (route different from the rear end);

Use vue-router in the vue

  1. Introducing vue-router component class library:
<!-- 1. 导入 vue-router 组件类库 -->
  <script src="./lib/vue-router-2.7.0.js"></script>
  1. Using the router-link assembly to navigate
<!-- 2. 使用 router-link 组件来导航 -->
<router-link to="/login">登录</router-link>
<router-link to="/register">注册</router-link>
  1. Using the router-view display of the matched component to component
<!-- 3. 使用 router-view 组件来显示匹配到的组件 -->
<router-view></router-view>
  1. Created using the Vue.extendCreate the component
// 4.1 使用 Vue.extend 来创建登录组件
var login = Vue.extend({
  template: '<h1>登录组件</h1>'
});

// 4.2 使用 Vue.extend 来创建注册组件
var register = Vue.extend({
  template: '<h1>注册组件</h1>'
});
  1. Create a routing router instance, to define routing rules match by routers property
// 5. 创建一个路由 router 实例,通过 routers 属性来定义路由匹配规则
var router = new VueRouter({
    routes: [
        { path: '/login', component: login },
        { path: '/register', component: register }
    ]
});
  1. Use router attribute to use routing rules
// 6. 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
    el: '#app',
    router: router // 使用 router 属性来使用路由规则
});

Parameters defined in the routing rules

  1. Parameters defined in the rule:
{ path: '/register/:id', component: register }
  1. By this.$route.paramsacquiring the parameters of the route:
var register = Vue.extend({
    template: '<h1>注册组件 --- {{this.$route.params.id}}</h1>'
});

Use childrenproperty nested implement routing

<div id="app">
    <router-link to="/account">Account</router-link>
    <router-view></router-view>
</div>

<script>
    // 父路由中的组件
    const account = Vue.extend({
      template: `<div>
        这是account组件
        <router-link to="/account/login">login</router-link> | 
        <router-link to="/account/register">register</router-link>
        <router-view></router-view>
      </div>`
    });

    // 子路由中的 login 组件
    const login = Vue.extend({
      template: '<div>登录组件</div>'
    });

    // 子路由中的 register 组件
    const register = Vue.extend({
      template: '<div>注册组件</div>'
    });

    // 路由实例
    var router = new VueRouter({
      routes: [
        { path: '/', redirect: '/account/login' }, // 使用 redirect 实现路由重定向
        {
          path: '/account',
          component: account,
          children: [ // 通过 children 数组属性,来实现路由的嵌套
            { path: 'login', component: login }, // 注意,子路由的开头位置,不要加 / 路径符
            { path: 'register', component: register }
          ]
        }
      ]
    });

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {},
      components: {
        account
      },
      router: router
    });
</script>

Named achieve classic layout view

  1. Tags code structure:
<div id="app">
    <router-view></router-view>
    <div class="content">
        <router-view name="a"></router-view>
        <router-view name="b"></router-view>
    </div>
</div>
  1. JS code:
<script>
    var header = Vue.component('header', {
      template: '<div class="header">header</div>'
    });

    var sidebar = Vue.component('sidebar', {
      template: '<div class="sidebar">sidebar</div>'
    });

    var mainbox = Vue.component('mainbox', {
      template: '<div class="mainbox">mainbox</div>'
    });

    // 创建路由对象
    var router = new VueRouter({
      routes: [
        {
          path: '/', components: {
            default: header,
            a: sidebar,
            b: mainbox
          }
        }
      ]
    });

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {},
      router
    });
</script>
  1. CSS style:
<style>
    .header {
      border: 1px solid red;
    }

    .content{
      display: flex;
    }
    .sidebar {
      flex: 2;
      border: 1px solid green;
      height: 500px;
    }
    .mainbox{
      flex: 8;
      border: 1px solid blue;
      height: 500px;
    }
</style>

watchUsing the Monitor property

Want to achieve and the contents of two text boxes change the value in the textbox full name change too;

  1. Monitor dataattribute changes:
<div id="app">
    <input type="text" v-model="firstName"> +
    <input type="text" v-model="lastName"> =
    <span>{{fullName}}</span>
</div>

<script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        firstName: 'jack',
        lastName: 'chen',
        fullName: 'jack - chen'
      },
      methods: {},
      watch: {
        'firstName': function (newVal, oldVal) { // 第一个参数是新数据,第二个参数是旧数据
          this.fullName = newVal + ' - ' + this.lastName;
        },
        'lastName': function (newVal, oldVal) {
          this.fullName = this.firstName + ' - ' + newVal;
        }
      }
    });
</script>
  1. Monitor routing object changes:
<div id="app">
    <router-link to="/login">登录</router-link>
    <router-link to="/register">注册</router-link>

    <router-view></router-view>
</div>

<script>
    var login = Vue.extend({
      template: '<h1>登录组件</h1>'
    });

    var register = Vue.extend({
      template: '<h1>注册组件</h1>'
    });

    var router = new VueRouter({
      routes: [
        { path: "/login", component: login },
        { path: "/register", component: register }
      ]
    });

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {},
      router: router,
      watch: {
        '$route': function (newVal, oldVal) {
          if (newVal.path === '/login') {
            console.log('这是登录组件');
          }
        }
      }
    });
</script>

computedUsing the calculated property

  1. Only the default gettercalculated property:
<div id="app">
    <input type="text" v-model="firstName"> +
    <input type="text" v-model="lastName"> =
    <span>{{fullName}}</span>
  </div>

  <script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        firstName: 'jack',
        lastName: 'chen'
      },
      methods: {},
      computed: { // 计算属性; 特点:当计算属性中所依赖的任何一个 data 属性改变之后,都会重新触发 本计算属性 的重新计算,从而更新 fullName 的值
        fullName() {
          return this.firstName + ' - ' + this.lastName;
        }
      }
    });
  </script>
  1. It has the definition getterand settercalculation of properties:
<div id="app">
    <input type="text" v-model="firstName">
    <input type="text" v-model="lastName">
    <!-- 点击按钮重新为 计算属性 fullName 赋值 -->
    <input type="button" value="修改fullName" @click="changeName">

    <span>{{fullName}}</span>
</div>

<script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        firstName: 'jack',
        lastName: 'chen'
      },
      methods: {
        changeName() {
          this.fullName = 'TOM - chen2';
        }
      },
      computed: {
        fullName: {
          get: function () {
            return this.firstName + ' - ' + this.lastName;
          },
          set: function (newVal) {
            var parts = newVal.split(' - ');
            this.firstName = parts[0];
            this.lastName = parts[1];
          }
        }
      }
    });
</script>

watch, computedAnd the methodscontrast between

  1. computedThe results are cached attributes, the attribute change responsive unless dependent recalculated only. The main property to use as;
  2. methodsThe method represents a particular operation, main writing business logic;
  3. watchAn object key is an expression of the need to observe the value corresponding callback function. It is mainly used to monitor specific changes in the data, thereby performing certain business logic operation; can be considered computedand methodsa combination thereof;

nrmThe installation

Role: to provide some of the most commonly used NPM package mirror address, allows us to quickly switch to install the server address of the packet time;
what is the mirror image: the original package very beginning is only present in the foreign NPM server, but due to network reasons, often not visit this time, we can at home, and create a NPM official website exactly the same server, but the data are taking over from where people, in addition, using exactly the same way;

  1. Run npm i nrm -gglobal installation nrmpackage;
  2. Use nrm lsView all available current mirror source address and the source address of the current mirror being used;
  3. Use nrm use npmor nrm use taobaoswitch between mirror source address;

Guess you like

Origin www.cnblogs.com/mumuyinxin/p/12122217.html