zoukankan      html  css  js  c++  java
  • vue基础语法(一)

    好久没更了,从零学习vue ,分批慢慢更

    框架和库的区别

    • 框架:是一套完整的解决方案;对项目的侵入性较大,项目如果需要更换框架,则需要重新架构整个项目。

    • node 中的 express;

    • 库(插件):提供某一个小功能,对项目的侵入性较小,如果某个库无法完成某些需求,可以很容易切换到其它库实现需求。

       

    Node(后端)中的 MVC 与 前端中的 MVVM 之间的区别

    • MVC 是后端的分层开发概念;

    • MVVM是前端视图层的概念,主要关注于 视图层分离,也就是说:MVVM把前端的视图层,分为了 三部分 Model, View , VM ViewModel

    • 为什么有了MVC还要有MVVM

      

    <body>
    <!--  将来new的vue实例会控制这个元素的所有内容-->
    <!--    vue实例所控制的这个元素区域就是我们的v-->
       <div id="app">
           <p>{{msg}}</p>
       </div>
    
        <script>
            // 创建一个Vue实例
            //new出来的vm对虾做哪个就是MVVM中的VM调度者
            var vm = new Vue({
                el: '#app', //表示当前new的这个vue实例要控制页面上的哪个区域
                //这里的data就是MVVM中的M,专门保存每个页面的数据
                data:{ //存放的是el中要用到的数据
                    msg: ''  //通过vue提供的指令很方便的渲染无需手动操作DOM
    
                }
            })
        </script>
    </body>
    <body>
    <div></div>
    <script>
        //v-cloak 解决插值表达式闪烁问题 dispaly:none
        //v-text会覆盖元素原本内容
        //v-html
        // type="button" value="按钮" v-bind:title="mytitle"
        // v-bind:  是vue中提供的用来绑定属性的指令 可以简写为一个:
        //v-on: 事件绑定机制 缩写是@
        methods:{
            //这个属性定义了当前vue实例的所有可用方法
        }
    </script>
    </body>

    跑马灯案例

    <template>
      <div class="home">
        <input type="button" value="浪起来" @click="lang" />
        <input type="button" value="猥琐点" @click="stop" />
        <h4>{{ msg }}</h4>
      </div>
    </template>
    
    <script>
    export default {
      //name: '跑马灯',
      //按钮绑定点击事件 v-on  事件处理函数中写相关的业务逻辑 拿到msg调用substring字符串截取第一个放最后,之后放入一个定时器
      components: {},
      data() {
        return {
          msg: '猥琐发育,别浪~~',
          intervalId: null
        }
      },
      methods: {
        lang() {
          //console.log(this.msg)
          if (this.intervalId != null) return
          this.intervalId = setInterval(() => {
            let start = this.msg.substring(0, 1)
            let end = this.msg.substring(1)
            this.msg = end + start
          }, 400)
        },
        stop() {
          clearInterval(this.intervalId)
          this.intervalId = null
        }
      }
    }
    </script>

    事件修饰符

    <template>
      <div class="home">
        <div class="inner" @click="divHandler">
          <input type="button" value="戳他" @click.stop="btHandler" />
          <!-- .stop阻止冒泡 -->
        </div>
        <a href="http://www.baidu.com" @click.prevent="link">有问题去百度</a>
        <!-- .prevent 阻止默认行为 -->
        <!-- .capture 实现捕获触发事件机制 -->
        <!-- .self只有点击当前元素是才会触发事件处理函数 只阻止自己的 -->
        <!-- .once 只触发一次事件处理函数 -->
      </div>
    </template>
    
    <script>
    export default {
      components: {},
      dtat() {},
      methods: {
        divHandler() {
          console.log('触发div点击')
        },
        btHandler() {
          console.log('触发按钮点击事件')
        },
        link() {
          console.log('触发了连接事件')
        }
      }
    }
    </script>
    <style scoped>
    .inner {
      height: 150px;
      background-color: cornflowerblue;
    }</style
    >

    双向绑定

    <template>
      <div class="home">
        <h4>{{ msg }}</h4>
        <input type="text" v-bind:value="msg" />
        <!-- v-bind:只能单向绑定 -->
        <input type="text" v-model="msg" />
        <!-- v-model 只能用在表单元素中  input(radio,text,address,email...)   select    checkbox   textarea  -->
      </div>
    </template>
    
    <script>
    export default {
      components: {},
      data() {
        return {
          msg: '宝马雕车香满路,玉壶光转,一夜鱼龙舞'
        }
      },
      methods: {}
    }
    </script>

    简易计算器

    <template>
      <div class="home">
        <input type="text" v-model="n1" />
    
        <select v-model="opt">
          <option value="+">+</option>
          <option value="-">-</option>
          <option value="*">*</option>
          <option value="/">/</option>
        </select>
        <input type="text" v-model="n2" />
        <input type="button" value="=" @click="calc" />
        <input type="text" v-model="result" />
      </div>
    </template>
    
    <script>
    export default {
      components: {},
      data() {
        return {
          n1: 0,
          n2: 0,
          result: 0,
          opt: '+'
        }
      },
      methods: {
        calc() {
          /*switch (this.opt) {
            case '+':
              this.result = parseInt(this.n1) + parseInt(this.n2)
              break
            case '-':
              this.result = parseInt(this.n1) - parseInt(this.n2)
              break
            case '*':
              this.result = parseInt(this.n1) * parseInt(this.n2)
              break
            case '/':
              this.result = parseInt(this.n1) / parseInt(this.n2)
              break
          }*/
          //正式开发中不建议用eval
          let codeStr = 'parseInt(this.n1)' + this.opt + 'parseInt(this.n2)'
          this.result = eval(codeStr)
        }
      }
    }
    </script>

    迭代

    <template>
      <div class="home">
        <p v-for="(item, i) in list" :key="item">
          索引值{{ i }}---每一项{{ item }}
        </p>
        <p v-for="user in lis" :key="user">{{ user.id }}-----{{ user.name }}</p>
        <p v-for="(val, key, i) in use" :key="val">
          值{{ val }}----键{{ key }}---索引{{ i }}
        </p>
        <p v-for="count in 10" :key="count">这是第{{ count }}次循环</p>
      </div>
    </template>
    
    <script>
    export default {
      components: {},
      data() {
        return {
          list: [1, 2, 3, 4, 5, 6],
          lis: [
            { id: 1, name: 'vivin' },
            { id: 2, name: 'vivin' },
            { id: 3, name: 'vivin' },
            { id: 4, name: 'vivin' },
            { id: 5, name: 'vivin' },
            { id: 6, name: 'vivin' }
          ],
          use: {
            //id: 1,
            name: 'vivin不是薇安',
            gender: 'woman'
          }
        }
      }
    }
    </script>

    v-if与v-show

    <template>
      <div class="home">
        <input type="button" value="toggle" @click="flag = !flag" />
        <h3 v-if="flag">v-if控制的元素</h3>
        <h3 v-show="flag">v-show控制的元素</h3>
        <!-- v-if 每次都会重新删除或新建元素较高的切换性能消耗  若元素涉及到频繁的切换不建议使用
         v-show  每次不会重新进行DOM的删除和创建元素只是切换了元素的 display:none 样式 较高的初始渲染消耗  -->
      </div>
    </template>
    
    <script>
    export default {
      components: {},
      data() {
        return {
          flag: true
        }
      },
      methods: {
        toggel() {
          this.flag = !this.flag
        }
      }
    }
    </script>

    添加删除品牌案例

    <template>
      <div class="home">
        <div>
          <div>
            <h3>添加品牌</h3>
          </div>
          <div>
            <label>
              ID:
              <input type="text" v-model="id" />
            </label>
            <label>
              Name:
              <input type="text" v-model="name" @keyup.f2="add" />
            </label>
            <label>
              <input type="button" value="添加" @click="add()" />
            </label>
            <label>
              关键词查找名词:
              <input
                type="text"
                v-model="keyword"
                id="search"
                v-focus
                v-color="'#cf6868'"
              />
            </label>
          </div>
        </div>
        <table style="100%">
          <thead style="height:50px,100%">
            <tr>
              <th>ID</th>
              <th>NAME</th>
              <th>Ctime</th>
              <th>Operation</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in search(keyword)" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.ctime | dateFormat('yyyy-MM-DD-hh-mm-ss') }}</td>
              <td>
                <a href="" @click.prevent="del(item.id)">删除</a>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="app2">
          <h3 v-color="'#fcd0d0'">{{ dt | dateFormat }}</h3>
        </div>
      </div>
    </template>
    <script>
    export default {
      components: {},
      data() {
        return {
          id: '',
          name: '',
          keyword: '',
          dt: new Date(),
          list: [
            { id: 1, name: '甘罗', ctime: new Date() },
            { id: 2, name: '扶苏', ctime: new Date() },
            { id: 3, name: '胡亥', ctime: new Date() },
            { id: 4, name: '医生', ctime: new Date() }
          ]
        }
      },
      methods: {
        add() {
          console.log('object')
          //获取idname从data上,组织一个对象这个对象调用数组的相关方法添加到当前data的list中
          let car = { id: this.id, name: this.name, ctime: new Date() }
          this.list.push(car)
          this.id = this.name = ''
        },
        del(id) {
          //let that = this
          //   this.list.some((item, i) => {
          //     if (item.id == id) {
          //       this.list.splice(i, 1)
          //       return true
          //     }
          //   })
          let index = this.list.findIndex(item => {
            if (item.id == id) {
              return true
            }
          })
          //console.log(index)
          this.list.splice(index, 1)
        },
        search(keyword) {
          //   let newList = []
          //   this.list.forEach(item => {
          //     if (item.name.indexOf(keyword) != -1) {
          //       newList.push(item)
          //     }
          //   })
          //   return newList
          // foreavh  some   filter  findIndex  这都属于数组新方法,都会对数组的每一项进行遍历
          return this.list.filter(item => {
            //ES6为字符串提供了一个新方法,叫做  String.prototype.includes('要包含的字符串') 如果包含返回true
            if (item.name.includes(keyword)) {
              return item
            }
          })
        }
      }
    }
    </script>
    import Vue from 'vue'
    import App from './App.vue'
    
    import VueResource from 'vue-resource'
    
    import router from './router'
    
    import animated from 'animate.css' // npm install animate.css --save安装,再引入
    Vue.use(animated)
    
    Vue.config.productionTip = false
    
    Vue.use(VueResource)
    
    //自定义全局按键修饰符
    Vue.config.keyCodes.f2 = 113
    
    //自定义指令  使用Vue.directive()定义的全局指令
    //其中参数一:指令的名称,定义的时候指令名称前不需要加v- 调用时需要
    //参数二是一个对象它身上有一些指令相关的钩子函数,这些函数在特定阶段执行相关操作
    Vue.directive('focus', {
      bind: function() {
        // 每当指令绑定到元素上的时候,会立即执行这个函数只执行一次
        // 在元素刚绑定指令时还没插入到DOM中,一个元素只有插入DOM之后才能获取焦点
        //el.focus() //第一个参数永远是el表示被绑定了指令的那个元素,是一个原生的js对象
      },
      inserted: function(el) {
        // inserted 表示元素插入到DOM中的时候,会执行inserted函数【触发一次】
        // 和js行为有关的操作最好在inserted中去执行,防止js行为不生效
        el.focus()
      },
      updated: function() {
        // 当VNode更新的时候,会执行updated,可能会触发多次
      }
    })
    
    // 自定义一个设置字体颜色的指令
    Vue.directive('color', {
      // 样式,只要通过指令绑定给了元素,不管这个元素有没有插入到页面中去,这个元素肯定有了一个内联样式
      // 将来元素肯定会显示到页面中去,这时候,浏览器的渲染引擎必然会解析央视,应用给这个元素
      bind: function(el, binding) {
        // el.style.color = 'red' // 和样式相关的操作一般可以在bind执行
        // console.log(binding.name)
        // console.log(binding.value)
        // console.log(binding.expression)
        el.style.color = binding.value
      }
    })
    
    // 过滤器的定义语法
    // Vue.filter('过滤器的名称',funtion(){})
    // 过滤器中的function第一个参数已经被规定死了永远都是过滤器管道符前面传递过来的数据
    // 过滤器调用的时候,采用的是就近原则,如果有私有过滤器和全局过滤器名字一致了,这时候优先调用私有
    // 全局过滤器进行时间格式化
    Vue.filter('dateFormat', function(dateStr, pattern) {
      // 根据给定的时间字符串得到特定的时间
      let dt = new Date(dateStr)
    
      // yyy-mm=dd
      let y = dt.getFullYear()
      let m = (dt.getMonth() + 1).toString().padStart(2, '0')
      let d = dt
        .getDate()
        .toString()
        .padStart(2, '0')
    
      //return y + '-' + m + '-' + d
      //return '${y}-${m}-${d}' //模板字符串
      if (pattern && pattern.toLowerCase() === 'yyyy-mm-dd') {
        // return y + '-' + m + '-' + d
        return `${y}-${m}-${d}`
      } else {
        let hh = dt
          .getHours()
          .toString()
          .padStart(2, '0')
        let mm = dt
          .getMinutes()
          .toString()
          .padStart(2, '0')
        let ss = dt
          .getSeconds()
          .toString()
          .padStart(2, '0')
    
        return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
      }
    })
    
    new Vue({
      router,
      render: h => h(App)
    }).$mount('#app')

    (ps:今天也是想ta的一天呢)

  • 相关阅读:
    使用video.js支持flv格式
    微信小程序开发(一)
    python advanced programming ( II )
    python advanced programming ( I )
    HTML/CSS
    info AI drive
    python基础回顾
    计算机组成原理2
    6.00.1x Introduction to computation
    有一种感动叫ACM(记陈立杰在成都赛区开幕式上的讲话)
  • 原文地址:https://www.cnblogs.com/vivin-echo/p/13848360.html
Copyright © 2011-2022 走看看