02 views

Vue.js - Day2

Brand Management

Add a new brand

Delete Brand

According condition filter Brand

  1. 1.x version filterBy instructions in 2.x has been abolished:

filterBy - instructions


<tr v-for="item in list | filterBy searchName in 'name'">

  <td>{{item.id}}</td>

  <td>{{item.name}}</td>

  <td>{{item.ctime}}</td>

  <td>

    <a href="#" @click.prevent="del(item.id)">删除</a>

  </td>

</tr>
  1. In version 2.x achieve screened manually :
  • Screening box bound to the VM instance searchNameattributes:

<hr> 输入筛选名称:

<input type="text" v-model="searchName">
  • In use v-for, when each line of data the instruction loop, no longer directly item in list, but inmethods of filtration method, while the filter conditions searchNamepassing in:

<tbody>

      <tr v-for="item in search(searchName)">

        <td>{{item.id}}</td>

        <td>{{item.name}}</td>

        <td>{{item.ctime}}</td>

        <td>

          <a href="#" @click.prevent="del(item.id)">删除</a>

        </td>

      </tr>

    </tbody>
  • searchFiltration method, the array filtermethod of filtering:

search(name) {

  return this.list.filter(x => {

    return x.name.indexOf(name) != -1;

  });

}

Vue debugging tools vue-devtoolsto install and use steps

Vue.js devtools - over the wall installation - Recommended

filter

The concept: Vue.js allows you to customize filters, can be used as a common text formatting . Filters can be used in two places: Mustache interpolation and v-bind expression . The filter should be added at the end of the JavaScript expression, a "pipe" which is indicated;

Private Filters

  1. HTML elements:

<td>{{item.ctime | dataFormat('yyyy-mm-dd')}}</td>
  1. Private filters-defined method:

filters: { // 私有局部过滤器,只能在 当前 VM 对象所控制的 View 区域进行使用

    dataFormat(input, pattern = "") { // 在参数列表中 通过 pattern="" 来指定形参默认值,防止报错

      var dt = new Date(input);

      // 获取年月日

      var y = dt.getFullYear();

      var m = (dt.getMonth() + 1).toString().padStart(2, '0');

      var d = dt.getDate().toString().padStart(2, '0');



      // 如果 传递进来的字符串类型,转为小写之后,等于 yyyy-mm-dd,那么就返回 年-月-日

      // 否则,就返回  年-月-日 时:分:秒

      if (pattern.toLowerCase() === 'yyyy-mm-dd') {

        return `${y}-${m}-${d}`;

      } else {

        // 获取时分秒

        var hh = dt.getHours().toString().padStart(2, '0');

        var mm = dt.getMinutes().toString().padStart(2, '0');

        var ss = dt.getSeconds().toString().padStart(2, '0');



        return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;

      }

    }

  }

Using the new method of String.prototype.padStart string ES6 (maxLength, fillString = '') or String.prototype.padEnd (maxLength, fillString = '') to fill the string;

Global Filters


// 定义一个全局过滤器

Vue.filter('dataFormat', function (input, pattern = '') {

  var dt = new Date(input);

  // 获取年月日

  var y = dt.getFullYear();

  var m = (dt.getMonth() + 1).toString().padStart(2, '0');

  var d = dt.getDate().toString().padStart(2, '0');



  // 如果 传递进来的字符串类型,转为小写之后,等于 yyyy-mm-dd,那么就返回 年-月-日

  // 否则,就返回  年-月-日 时:分:秒

  if (pattern.toLowerCase() === 'yyyy-mm-dd') {

    return `${y}-${m}-${d}`;

  } else {

    // 获取时分秒

    var hh = dt.getHours().toString().padStart(2, '0');

    var mm = dt.getMinutes().toString().padStart(2, '0');

    var ss = dt.getSeconds().toString().padStart(2, '0');



    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;

  }

});

Note: When there are two local and global same name filter time, will be called to the principle of proximity, namely: local filter precedence over global filter is called!

Keyboard modifiers and custom keyboard modifiers

1.x custom keyboard modifiers [to understand]


Vue.directive('on').keyCodes.f2 = 113;

2.x custom keyboard modifiers

  1. By Vue.config.keyCodes.名称 = 按键值aliases to customize the case modifier:

Vue.config.keyCodes.f2 = 113;
  1. Using a custom key modifier:

<input type="text" v-model="name" @keyup.f2="add">

Custom command

  1. Custom global and local custom instructions:

    // 自定义全局指令 v-focus,为绑定的元素自动获取焦点:

    Vue.directive('focus', {

      inserted: function (el) { // inserted 表示被绑定元素插入父节点时调用

        el.focus();

      }

    });



    // 自定义局部指令 v-color 和 v-font-weight,为绑定的元素设置指定的字体颜色 和 字体粗细:

      directives: {

        color: { // 为元素设置指定的字体颜色

          bind(el, binding) {

            el.style.color = binding.value;

          }

        },

        'font-weight': function (el, binding2) { // 自定义指令的简写形式,等同于定义了 bind 和 update 两个钩子函数

          el.style.fontWeight = binding2.value;

        }

      }
  1. Use custom instructions:

<input type="text" v-model="searchName" v-focus v-color="'red'" v-font-weight="900">

Vue 1.x custom instruction [deprecated elements, can understand]

Vue.elementDirective('red-color', {
  bind: function () {
    this.el.style.color = 'red';
  }
});

Use:

<red-color>1232</red-color>

Examples of the life cycle of vue

  • What is the life cycle: from creation Vue instance, to run, to destroy the period, always accompanied by a variety of events, which, collectively referred to as life cycle!
  • Lifecycle hook : is the alias of life cycle events only;
  • Lifecycle hook function = = life cycle life cycle events
  • The main function of the life cycle Category:
  • During the life cycle of creation functions:
    • beforeCreate: Just instance is created in memory, this time, there is no good data to initialize properties and methods
    • created: OK instance has been created in memory, this time data and methods have been created OK, this time has not yet begun to compile a template
    • beforeMount: At this point it has been compiled template, but have not mounted to the page
    • mounted: At this point, has compiled template, mounted to the page specified container display
  • During the life cycle of the run function:
    • beforeUpdate: This function is executed before a status update, this time in the state value data is up to date, but the data displayed on the screen or old, because at this time has not yet begun to re-render a DOM node
    • updated: This function is called after the update is completed instance, data is displayed on the data values ​​in the state and interfaces, have completed the update, the interface has been re-rendered good!
  • During the life cycle of destruction function:
    • beforeDestroy: called before destroy instance. In this step, the instance is still fully available.
    • destroyed: Vue instance called after the destruction. After the call, everything will de-binding indication Vue instance, all event listeners will be removed, all the child instance will be destroyed.

vue-resource achieve get, post, jsonp request

In addition vue-resource, you may be used axiosto third packet to fulfill the request for data

  1. Before learning how to initiate a data request?
  2. Common data type of request? get post jsonp
  3. Test URL address of the requested resource:
  • get request Address: http://vue.studyit.io/api/getlunbo
  • post request Address: http: //vue.studyit.io/api/post
  • jsonp request Address: http: //vue.studyit.io/api/jsonp
  1. The principle of JSONP
  • Due to security restrictions browser, AJAX does not allow access to different protocols, different domain name and port number of different data interface, the browser that this visit unsafe;
  • Can be dynamically created script tag form, the src attribute of the script tag, data at the address of the interface, because there is no limit cross-domain script tag, this manner of data acquisition, called JSONP (Note: The implementation principle of JSONP, its , JSONP support only Get request);
  • The specific implementation process:
    • Define a client callback method, predefined operations on the data;
    • Then the name of the callback method by URL parameter passing form, submit the data interface to the server;
    • Organize server data interface to send data to the client, the client then took the passed callback method name, a string of splicing a call to this method, sent to the client to parse executed;
    • After the string returned by the server to get the client, as the Script script to parse executed, so it can get a JSONP data;
  • With that through Node.js, done manually request a JSONP example;
   const http = require('http');
   // 导入解析 URL 地址的核心模块
   const urlModule = require('url');

   const server = http.createServer();
   // 监听 服务器的 request 请求事件,处理每个请求
   server.on('request', (req, res) => {
     const url = req.url;

     // 解析客户端请求的URL地址
     var info = urlModule.parse(url, true);

     // 如果请求的 URL 地址是 /getjsonp ,则表示要获取JSONP类型的数据
     if (info.pathname === '/getjsonp') {
       // 获取客户端指定的回调函数的名称
       var cbName = info.query.callback;
       // 手动拼接要返回给客户端的数据对象
       var data = {
         name: 'zs',
         age: 22,
         gender: '男',
         hobby: ['吃饭', '睡觉', '运动']
       }
       // 拼接出一个方法的调用,在调用这个方法的时候,把要发送给客户端的数据,序列化为字符串,作为参数传递给这个调用的方法:
       var result = `${cbName}(${JSON.stringify(data)})`;
       // 将拼接好的方法的调用,返回给客户端去解析执行
       res.end(result);
     } else {
       res.end('404');
     }
   });

   server.listen(3000, () => {
     console.log('server running at http://127.0.0.1:3000');
   });
  1. vue-resource configuration steps:
  • Directly in the page, by scriptthe label, the introduction of vue-resourcethe script file;
  • Note: the order is quoted: quote from Vuethe script file, and then referenced vue-resourcescript file;
  1. Send a get request:
getInfo() { // get 方式获取数据
  this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
    console.log(res.body);
  })
}
  1. Send a post request:
postInfo() {
  var url = 'http://127.0.0.1:8899/api/post';
  // post 方法接收三个参数:
  // 参数1: 要请求的URL地址
  // 参数2: 要发送的数据对象
  // 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
  this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
    console.log(res.body);
  });
}
  1. JSONP request the data transmission:
jsonpInfo() { // JSONP形式从服务器获取数据
  var url = 'http://127.0.0.1:8899/api/jsonp';
  this.$http.jsonp(url).then(res => {
    console.log(res.body);
  });
}

Configuring the local database and data interface (API)

  1. First-extracting installation PHPStudy;
  2. Extracting installer Navicatdatabase visualization tool, and activation;
  3. Open the Navicattool, create a new blank database named dtcmsdb4;
  4. Double-click the new database, the database connection on this gap in the new database 右键-> 运行SQL文件select and execute dtcmsdb4.sqlthe database script file; if not execution error, the database import is complete;
  5. Into the folder vuecms3_nodejsapiinside, perform npm iinstallation of all dependencies;
  6. Make sure the machine is installed nodemon, is not installed, run npm i nodemon -gglobally installation, after installation, enter the vuecms3_nodejsapidirectory -> srcContents -> double click to runstart.bat
  7. If the API fails to start, check whether PHPStudy normally open, while checking app.jsin on 14行the database connection string is configured correctly; PHPStudy default user name is root, the default password is also root

Brand management reform

Showcase the brand list

Add brand data

Brand delete data

Vue animation

Why should Animation: Animation can improve the user experience to help users better understand the function of the page;

Use transition class name

  1. HTML structure:
<div id="app">
    <input type="button" value="动起来" @click="myAnimate">
    <!-- 使用 transition 将需要过渡的元素包裹起来 -->
    <transition name="fade">
      <div v-show="isshow">动画哦</div>
    </transition>
  </div>
  1. VM instance:
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
  el: '#app',
  data: {
    isshow: false
  },
  methods: {
    myAnimate() {
      this.isshow = !this.isshow;
    }
  }
});
  1. Define two sets of class styles:
/* 定义进入和离开时候的过渡状态 */
    .fade-enter-active,
    .fade-leave-active {
      transition: all 0.2s ease;
      position: absolute;
    }

    /* 定义进入过渡的开始状态 和 离开过渡的结束状态 */
    .fade-enter,
    .fade-leave-to {
      opacity: 0;
      transform: translateX(100px);
    }

CSS animation using third-party libraries

  1. Import animation library:
<link rel="stylesheet" type="text/css" href="./lib/animate.css">
  1. Define transition and attributes:
<transition
    enter-active-class="fadeInRight"
    leave-active-class="fadeOutRight"
    :duration="{ enter: 500, leave: 800 }">
    <div class="animated" v-show="isshow">动画哦</div>
</transition>

Animation hook function

  1. And a transition assembly defines three hook function:
<div id="app">
    <input type="button" value="切换动画" @click="isshow = !isshow">
    <transition
    @before-enter="beforeEnter"
    @enter="enter"
    @after-enter="afterEnter">
      <div v-if="isshow" class="show">OK</div>
    </transition>
  </div>
  1. Method hook defines three methods:
methods: {
        beforeEnter(el) { // 动画进入之前的回调
          el.style.transform = 'translateX(500px)';
        },
        enter(el, done) { // 动画进入完成时候的回调
          el.offsetWidth;
          el.style.transform = 'translateX(0px)';
          done();
        },
        afterEnter(el) { // 动画进入完成之后的回调
          this.isshow = !this.isshow;
        }
      }
  1. Length and style defined the transition animation:
.show{
      transition: all 0.4s ease;
    }

v-for transition list

  1. To define the transition style:
<style>
    .list-enter,
    .list-leave-to {
      opacity: 0;
      transform: translateY(10px);
    }

    .list-enter-active,
    .list-leave-active {
      transition: all 0.3s ease;
    }
</style>
  1. DOM structure is defined, which requires the use of transition-group component to wrap v-for circulation list:
  <div id="app">
    <input type="text" v-model="txt" @keyup.enter="add">

    <transition-group tag="ul" name="list">
      <li v-for="(item, i) in list" :key="i">{{item}}</li>
    </transition-group>
  </div>
  1. Definition of the VM structure:
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        txt: '',
        list: [1, 2, 3, 4]
      },
      methods: {
        add() {
          this.list.push(this.txt);
          this.txt = '';
        }
      }
    });

Sorting the list of transition

<transition-group>There is also a component special. Not only can enter and leave the animation, you can also change the orientation . To use this new feature need to know the new v-movefeatures, it will be applied in the process of changing the positioning of elements .

  • v-moveAnd v-leave-activetransition combination, can make the list more gentle and soft:
.v-move{
  transition: all 0.8s ease;
}
.v-leave-active{
  position: absolute;
}

related articles

  1. vue.js 1.x documents
  2. vue.js 2.x document
  3. String.prototype.padStart(maxLength, fillString)
  4. js inside the key code corresponding to the keyboard event
  5. pagekit/vue-resource
  6. Navicat how to import and export files sql sql file
  7. Bessel Online Generator

Guess you like

Origin www.cnblogs.com/huameixiao/p/11606085.html