Vue 前端框架

Vue

Vue 简介

Vue示例

Vue学习资源代码来自:how2java

利用Vue获取元素

下面是使用了js的实现方法:

<div id="div1">
   
</div>
  
<script>
  
//准备数据
var gareen = {"name":"盖伦","hp":616};
 
//获取 html dom
var div1 = document.getElementById("div1");
 
//显示数据
div1.innerHTML= gareen.name;
  
</script>

使用Vue的实现方法:

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<div id="div1">
   
  {{gareen.name}}
 
</div>
  
<script>
  
//准备数据
var gareen = {"name":"盖伦","hp":616};
 
//通过vue.js 把数据和对应的视图关联起来
new Vue({
      el: '#div1',
      data: {
        message: gareen
      }
    })
  
</script>

实现的结果:
在div1里面:显示了盖伦两个字。

简单的点击计数器

<script src="http://how2j.cn/study/vue.min.js"></script>
  
<div id="div1">
  
  <div>一共点击了  {{clickNumber}}</div> 
  <button v-on:click="count">点击</button>
  
</div>
   
<script>
   
new Vue({
      el: '#div1',
      data: {
          clickNumber:0
      },
      methods:{
          count: function(){
              this.clickNumber++;
          }
      }
    })
   
</script>

其中,上面的v-on 可以替换为@。
显示结果:
在这里插入图片描述

事件冒泡

<script src="http://how2j.cn/study/vue.min.js"></script>
  
<style type="text/css">
   * {
       margin: 0 auto;
       text-align:center;
       line-height: 40px;
   }
   div {
       width: 100px;
       cursor:pointer;
   }
   #grandFather {
       background: green;
   }
   #father {
       background: blue;
   }
   #me {
       background: red;
   }#son {
        background: gray;
    }
</style>
     
<div id="content">
    <div id="grandFather"  v-on:click="doc">
        grandFather
        <div id="father" v-on:click="doc">
            father
            <div id="me" v-on:click="doc">
                me
                <div id="son" v-on:click="doc">
                son
            </div>
            </div>
        </div>
    </div>
 
</div>
   
<script>
    var content = new Vue({
        el: "#content",
        data: {
            id: ''
        },
        methods: {
            doc: function () {
                this.id= event.currentTarget.id;
                alert(this.id)
            }
        }
    })
</script>

运行的结果:
在这里插入图片描述
当我们点击son的时候,会依次弹出提示框son、me、father、grandfather这么消息。这么因为事件是冒泡的,事件会从最底层被点击元素开始往上传。

阻止冒泡

那么如果我们不想要上面的冒泡效果,怎么办呢?
需要的仅仅是一个冒泡修饰符.stop
<div id="me" v-on:click.stop="doc">,那么在me就会停止向上冒泡。

优先捕获

如果,我们想要某个元素的提示首先弹出来。
这就要用到优先捕获的概念了。
利用<div id="father" v-on:click.capture="doc">就可以让father率先捕获事件。

自己捕获

使用<div id="father" v-on:click.self="doc">后father,在点击其他子元素的时候,不再触发点击事件,只有点击其本身的时候才能触发。

提交一次

使用<div id="father" v-on:click.once="doc">中once修饰后,father只有第一次点击生效,随后的点击均不生效。

阻止跳转

.prevent可以阻止一个按钮点击的跳转,如果后面跟了函数,那么依然会执行。
下面是a、submit三个测试:

  • 第一个执行函数后正常跳转。
  • 第二个执行函数但不跳转。
  • 第三个不执行函数也不跳转。
<script src="http://how2j.cn/study/vue.min.js"></script>
  
<div id="div1">
  
  <a href="http://12306.com" @click="jump" >正常的链接 http://12306.com</a>
  
  <br>
  <a href="http://12306.com" @click.prevent="jump" >prevent jump()之后的链接 http://12306.com</a>
  <br>
  <a href="http://12306.com" @click.prevent >纯prevent之后的链接 http://12306.com</a>
  
  <br>
  <br>
  <form @submit="jump" action="http://12306.com">
  	<button type="submit">正常的form</button>
  </form>
  <form @submit.prevent="jump" action="http://12306.com">
  	<button type="submit">prevent jump()之后的form</button>
  </form>
  <form @submit.prevent action="http://12306.com">
  	<button type="submit">纯prevent之后的form</button>
  </form>
  
</div>
   
<script>
   
new Vue({
      el: '#div1',
      data: {
      },
      methods:{
    	  jump:function(){
    		  alert("jump()函数被调用");
    	  }
      }
    })
   
</script>

条件语句示例

if语句

下面是一个简单的if语句实现:

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<div id="div1">
   
  <button v-on:click="toggle">切换隐藏显示</button>
  <div v-if="show"> 默认这一条是看得见的</div>
     
</div>
    
<script>
    
new Vue({
      el: '#div1',
      data: {
          show:true
      },
      methods:{
          toggle: function(){
              this.show=!this.show;
          }
      }
    })
    
</script>
if-else语句
<script src="http://how2j.cn/study/vue.min.js"></script>
   
<div id="div1">
   
  <button v-on:click="moyiba"> 摸一把彩票 10%的几率,建议一边点击一边心里默数,多少次了,站长表示最多点了40次才中奖,妈蛋~ </button>
  <div v-if="show"> 中了500万!</div>
  <div v-else>谢谢惠顾!</div> 
     
</div>
    
<script>
    
new Vue({
      el: '#div1',
      data: {
          show:false
      },
      methods:{
          moyiba: function(){
             this.show=Math.random()<0.1
          }
      }
    })
    
</script>
if-elseif-else
<script src="http://how2j.cn/study/vue.min.js"></script>
   
<div id="div1">
   
  <button v-on:click="toutai"> 看看下辈子投胎是做什么的 </button>
  <div v-if="number>98"> 神仙</div>
  <div v-else-if="number>95"> 国家领导人</div>
  <div v-else-if="number>90"> 大富商</div>
  <div v-else-if="number>80"> 大企业主</div>
  <div v-else-if="number>70"> 演艺明星</div>
  <div v-else-if="number>60"> 小企业主</div>
  <div v-else-if="number>50"> 普通公务员</div>
  <div v-else-if="number>40"> 小个体户</div>
  <div v-else-if="number>30"> 血汗工厂工人</div>
  <div v-else-if="number>20"> 偏远山区农民</div>
  <div v-else> 流浪汉</div>
     
</div>
    
<script>
    
new Vue({
      el: '#div1',
      data: {
          number:0
      },
      methods:{
          toutai: function(){
             this.number=Math.random()*100
          }
      }
    })
    
</script>

for循环

基本用法
<script src="http://how2j.cn/study/vue.min.js"></script>
   
<style>
table tr td{
    border:1px solid gray;
}
table{
    border-collapse:collapse;
    width:300px;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
 
<div id="div1">
   
    <table align="center" >
        <tr class="firstLine">
            <td>name</td>
            <td>hp</td>
        </tr>
         
        <tr v-for="hero in heros">
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
        </tr>
         
    </table>
 
</div>
    
<script>
  
var data = [
          {name:"盖伦",hp:341},
          {name:"提莫",hp:225},
          {name:"安妮",hp:427},
          {name:"死歌",hp:893}
    ];
new Vue({
      el: '#div1',
      data: {
          heros:data
      }
    })
    
</script>

实现效果:
在这里插入图片描述

添加index

index从0开始:

<script src="http://how2j.cn/study/vue.min.js"></script>
   
<style>
table tr td{
    border:1px solid gray;
}
table{
    border-collapse:collapse;
    width:300px;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
 
<div id="div1">
   
    <table align="center" >
        <tr class="firstLine">
            <td>number</td>
            <td>name</td>
            <td>hp</td>
        </tr>
         
        <tr v-for="hero,index in heros">
            <td>{{index+1}}</td>
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
        </tr>
         
    </table>
 
</div>
    
<script>
  
var data = [
          {name:"盖伦",hp:341},
          {name:"提莫",hp:225},
          {name:"安妮",hp:427},
          {name:"死歌",hp:893}
    ];
new Vue({
      el: '#div1',
      data: {
          heros:data
      }
    })
    
</script>

实现效果:
在这里插入图片描述

纯数字循环
<script src="http://how2j.cn/study/vue.min.js"></script>
   
<div id="div1">
    <div v-for="i in 10">
     {{ i }}
    </div>
</div>
    
<script>
  
new Vue({
      el: '#div1'
    })
    
</script>

属性绑定

使用v-bind来实现属性的绑定。
其中v-bind可以省略不写。

<script src="http://how2j.cn/study/vue.min.js"></script>
   
<div id="div1">
    <a v-bind:href="page">http://12306.com</a>
</div>
    
<script>
  
new Vue({
      el: '#div1',
      data:{
          page:'http://12306.com'
      }
    })
    
</script>

双向绑定

即当我们表单要提交的时候,一开始先给它绑定一个初始值,但当实际后面使用的时候返回一个真实的输入值进行绑定。

下面就是一个简单的例子,使用了v-model来实现该效果:

<script src="http://how2j.cn/study/vue.min.js"></script>
   
<div id="div1">
     
    hero name: <input v-model="name" >
    <button @click="doClick" >提交数据</button>
     
</div>
    
<script>
  
new Vue({
      el: '#div1',
      data:{
        name:"teemo"
      },
      methods:{
          doClick:function(){
              alert(this.name);
          }
      }
    })
    
</script>

多种风格的数据绑定

<script src="http://how2j.cn/study/vue.min.js"></script>
    
<style>
table tr td{
    border:1px solid gray;
    padding:10px;
     
}
table{
    border-collapse:collapse;
    width:800px;
    table-layout:fixed;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
  
<div id="div1">
    
    <table align="center" >
        <tr class="firstLine">
            <td>视图类型</td>
            <td>输入数据</td>
            <td>绑定到Vue上的数值</td>
        </tr>       
        <tr>
            <td>
                单行文本
            </td>
            <td>
                <input v-model="input" placeholder="输入数据">
            </td>
            <td>
                <p>{{ input }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                多行文本
            </td>
            <td>
                <textarea v-model="textarea" placeholder="输入数据"></textarea>
            </td>
            <td>
                <p>{{ textarea }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                单个复选框
            </td>
            <td>
                <input type="checkbox" id="checkbox" v-model="checked">
            </td>
            <td>
                <p>{{ checked }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                多个复选框
            </td>
            <td>
                  <input type="checkbox" id="teemo" value="teemo" v-model="checkedes">
                  <label for="teemo">teemo</label>
                  <input type="checkbox" id="gareen" value="gareen" v-model="checkedes">
                  <label for="gareen">gareen</label>
                  <input type="checkbox" id="annie" value="annie" v-model="checkedes">
                  <label for="annie">annie</label>
            </td>
            <td>
                <p>{{ checkedes }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                单选按钮
            </td>
            <td>
              <input type="radio" id="one" value="One" v-model="radio">
              <label for="one">One</label>
              <br>
              <input type="radio" id="two" value="Two" v-model="radio">
              <label for="two">Two</label>
            </td>
            <td>
                <p>{{ radio }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                单选选择框
            </td>
            <td>
              <select v-model="selected" size="5">
                <option disabled value="">请选择</option>
                <option>AD</option>
                <option>AC</option>
                <option>ADC</option>
              </select>
            </td>
            <td>
                <p>{{ selected }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                多选选择框
            </td>
            <td>
              (通过ctrl或者shift进行多选)<br>
              <select v-model="selecteds" multiple size="5">
                <option disabled value="">请选择</option>
                <option>AD</option>
                <option>AC</option>
                <option>ADC</option>
              </select>
            </td>
            <td>
                <p>{{ selecteds }}</p>   
            </td>
        </tr>
        <tr>
            <td>
                单个复选框
            </td>
            <td>
                默认值是true或者false,也可以修改为自定义的值<br>
                <input type="checkbox" id="toggle" true-value="yes" false-value="no" v-model="toggle">
            </td>
            <td>
                <p>{{ toggle }}</p>   
            </td>
        </tr>       
 
    </table>
  
</div>
     
<script>
   
new Vue({
      el: '#div1',
      data: {
          input:'',
          textarea:'',
          checked:'',
          checkedes:[],
          radio:'',
          selected:'',
          selecteds:[],
          toggle:'',
           
      }
    })
     
</script>

运行结果如下:
在这里插入图片描述

.lazy

就像<input v-model.trim="input" placeholder="输入数据">
延迟属性的变化,等到完全数据,聚焦结束才进行属性变化。

.number

修饰过的输入,它会被定义为number类型。

.trim

修饰过的地方会自动删除字符串前后的空格。

数字计算

Vue中可以在{{x/y}}直接进行计算。

<script src="http://how2j.cn/study/vue.min.js"></script>
     
<style>
table tr td{
    border:1px solid gray;
    padding:10px;
      
}
table{
    border-collapse:collapse;
    width:800px;
    table-layout:fixed;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
   
<div id="div1">
     
    <table align="center" >
        <tr class="firstLine">
            <td>人民币</td>
            <td>美元</td>
        </tr>      
        <tr>
            <td align="center" colspan="2">
            汇率: <input type="number" v-model.number="exchange" />
            </td>
        </tr>
         
        <tr>
         
            <td align="center">: <input type="number" v-model.number = "rmb"  />
            </td>
            <td align="center">
                $: {{ rmb/exchange }}
            </td>
        </tr>
    </table>
   
</div>
      
<script>
    
new Vue({
      el: '#div1',
      data: {
          exchange:6.4,
          rmb:0
      }
    })
      
</script>

或者,也可以编写方法实现同样的效果{{ getDollar() }}
一般使用computed直接计算是有缓存的,可以节约重复计算时间。
运行结果:
在这里插入图片描述

watch来实现变量监听

下面的代码实现了跟上面一样的美元汇率兑换效果,当watch观察到rmb或者dollar的值变化,另一个也随之变化。

<script src="http://how2j.cn/study/vue.min.js"></script>
     
<style>
table tr td{
    border:1px solid gray;
    padding:10px;
      
}
table{
    border-collapse:collapse;
    width:800px;
    table-layout:fixed;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
   
<div id="div1">
     
    <table align="center" >
        <tr class="firstLine">
            <td>人民币</td>
            <td>美元</td>
        </tr>      
        <tr>
            <td align="center" colspan="2">
            汇率: <input type="number" v-model.number="exchange" />
            </td>
        </tr>
         
        <tr>
         
            <td align="center">: <input type="number" v-model.number = "rmb"  />
            </td>
            <td align="center">
                $: <input type="number" v-model.number = "dollar"   />
            </td>
        </tr>
    </table>
   
</div>
      
<script>
    
new Vue({
      el: '#div1',
      data: {
          exchange:6.4,
          rmb:0,
          dollar:0
      },
      watch:{
          rmb:function(val) {
              this.rmb = val;
              this.dollar = this.rmb / this.exchange;
          },
          dollar:function(val) {
              this.dollar = val;
              this.rmb = this.dollar * this.exchange;
          },
      }
       
    })
      
</script>

过滤器

首字母过滤器

下面我们构造一个简单的过滤器。

 filters:{
    	  capitalize:function(value) {
    		    if (!value) return '' //如果为空,则返回空字符串
    		    value = value.toString()
    		    return value.charAt(0).toUpperCase() + value.substring(1)
          }
      }

通过以下{{ data|capitalize }}来使用过滤器capitalize

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<style>
table tr td{
    border:1px solid gray;
    padding:10px;
      
}
table{
    border-collapse:collapse;
    width:800px;
    table-layout:fixed;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
   
<div id="div1">
     
    <table align="center" >
        <tr class="firstLine">
            <td>输入数据</td>
            <td>过滤后的结果</td>
        </tr>      
        <tr>
            <td align="center">
                <input v-model= "data"  />
            </td>
            <td align="center">
                {{ data|capitalize }}
            </td>
        </tr>
    </table>
   
</div>
      
<script>
    
new Vue({
      el: '#div1',
      data: {
          data:''
      },
      filters:{
          capitalize:function(value) {
                if (!value) return '' //如果为空,则返回空字符串
                value = value.toString()
                return value.charAt(0).toUpperCase() + value.substring(1)
          }
      }
    })
      
</script>

实现的效果:
在这里插入图片描述

多层过滤器

定义两个过滤器:
他们分别是首字母过滤器和尾字母过滤器。

filters:{
          capitalize:function(value) {
                if (!value) return '' //如果为空,则返回空字符串
                value = value.toString()
                return value.charAt(0).toUpperCase() + value.substring(1)
          },
          capitalizeLastLetter:function(value) {
                if (!value) return '' //如果为空,则返回空字符串
                value = value.toString()
                return value.substring(0,value.length-1)+ value.charAt(value.length-1).toUpperCase()
          }
      }

使用{{ data|capitalize|capitalizeLastLetter }}来使用多重过滤器capitalizecapitalizeLastLetter

全局过滤器

下面的代码使用了全局过滤器。

Vue.filter('capitalize', function (value) {
	if (!value) return ''
	value = value.toString()
	return value.charAt(0).toUpperCase() + value.slice(1)
})
Vue.filter('capitalizeLastLetter', function (value) {
	if (!value) return '' //如果为空,则返回空字符串
	value = value.toString()
	return value.substring(0,value.length-1)+ value.charAt(value.length-1).toUpperCase()
})

组件

就是说相当于一个模板,给他传不同的参数,实现不同的显示效果即可。
包含各种product。

简单的实现
<script src="http://how2j.cn/study/vue.min.js"></script>
 
<style>
div.product{
  float:left;
  border:1px solid lightGray;
  width:200px;
  margin:10px;
  cursor: pointer;
}
</style>
 
<div id="div1">
    <product></product>
    <product></product>
    <product></product>
</div>
  
<script>
new Vue({
  el: '#div1',
  components:{
      'product':{
          template:'<div class="product" >MAXFEEL休闲男士手包真皮手拿包大容量信封包手抓包夹包软韩版潮</div>'
      }
  }
})
</script>

实现效果:
在这里插入图片描述

全局方法
Vue.component('product', {
      template: '<div class="product" >MAXFEEL休闲男士手包真皮手拿包大容量信封包手抓包夹包软韩版潮</div>'
    })
 
引入参数

直接添写静态参数。

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<style>
div.product{
  float:left;
  border:1px solid lightGray;
  width:200px;
  margin:10px;
  cursor: pointer;
}
</style>
 
<div id="div1">
    <product name="MAXFEEL休闲男士手包真皮手拿包大容量信封包手抓包夹包软韩版潮"></product>
    <product name="宾度 男士手包真皮大容量手拿包牛皮个性潮男包手抓包软皮信封包"></product>
    <product name="唯美诺新款男士手包男包真皮大容量小羊皮手拿包信封包软皮夹包潮"></product>
</div>
  
<script>
Vue.component('product', {
      props:['name'],
      template: '<div class="product" >{{name}}</div>'
    })
 
new Vue({
  el: '#div1'
})
</script>
动态参数

使用前面的v-bind来实现。

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<style>
div.product{
  float:left;
  border:1px solid lightGray;
  width:200px;
  margin:10px;
  cursor: pointer;
}
</style>
 
<div id="div1">
    组件外的值:<input v-model="outName" ><br>
    <product v-bind:name="outName"></product>
</div>
  
<script>
Vue.component('product', {
      props:['name'],
      template: '<div class="product" >{{name}}</div>'
    })
 
new Vue({
  el: '#div1',
  data:{
      outName:'产品名称'
  }
})
</script>
点击事件
<script src="http://how2j.cn/study/vue.min.js"></script>
 
<style>
div.product{
  float:left;
  border:1px solid lightGray;
  width:200px;
  margin:10px;
  cursor: pointer;
}
</style>
 
<div id="div1">
    <product name="MAXFEEL休闲男士手包真皮手拿包大容量信封包手抓包夹包软韩版潮" sale="10" ></product>
    <product name="宾度 男士手包真皮大容量手拿包牛皮个性潮男包手抓包软皮信封包" sale="20" ></product>
    <product name="唯美诺新款男士手包男包真皮大容量小羊皮手拿包信封包软皮夹包潮" sale="30" ></product>
</div>
 
<script>
Vue.component('product', {
      props:['name','sale'],
      template: '<div class="product" v-on:click="increaseSale">{{name}} 销量: {{sale}} </div>',
      methods:{
          increaseSale:function(){
              this.sale++
          }
      }
    })
 
new Vue({
  el: '#div1'
})
</script>

实现效果:
点击一下增加销量。
在这里插入图片描述

使用json数组
 products:[
                {"name":"MAXFEEL休闲男士手包真皮手拿包大容量信封包手抓包夹包软韩版潮","sale":"18"},
                {"name":"宾度 男士手包真皮大容量手拿包牛皮个性潮男包手抓包软皮信封包","sale":"35"},
                {"name":"唯美诺新款男士手包男包真皮大容量小羊皮手拿包信封包软皮夹包潮","sale":"29"}
                ]
最终成果

下面的template,由于不好写可以外部写一个display:none的模板,然后通过
var tempalateDiv=document.getElementById("tempalate").innerHTML;获取。

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<style>
div.product{
  float:left;
  border:1px solid lightGray;
  width:200px;
  margin:10px;
  cursor: pointer;
}
div.product:hover{
  border:1px solid #c40000;
   
}
div.price{
  color:#c40000; 
  font-weight:bold;
  font-size:1.2em;
  margin:10px;
}
div.productName{
  color:gray;
  font-size:0.8em;
  margin:10px;
}
div.sale{
  float:left; 
  width:100px;
  border:1px solid lightgray;
  border-width:1px 0px 0px 0px;
  color:gray;
  font-size:0.8em;
  padding-left:10px;
}
div.review{
  overflow:hidden;
  border:1px solid lightgray;
  border-width:1px 0px 0px 1px;
  color:gray;
  font-size:0.8em; 
  padding-left:10px;
} 
</style>
 
<div id="tempalate" style="display:none">
    <div class="product" v-on:click="increaseSales">
        <div class="price">
                    ¥ {{product.price}}
        </div>
        <div class="productName">
            {{product.name}}
        </div>
        <div class="sale"> 月成交 {{product.sale}}</div>
        <div class="review"> 评价 {{product.review}} </div>
    </div>
</div>
 
<div id="div1">
    <product v-for="item in products" v-bind:product="item"></product>
</div>
  
<script>
var tempalateDiv=document.getElementById("tempalate").innerHTML;
var templateObject = {
    props: ['product'],
    template: tempalateDiv,
      methods: {
            increaseSales: function () {
                this.product.sale = parseInt(this.product.sale);
              this.product.sale += 1
              this.$emit('increment')
            }
          }
 
}
 
Vue.component('product', templateObject)
 
new Vue({
  el: '#div1',
  data:{
      products:[
                {"name":"MAXFEEL休闲男士手包真皮手拿包大容量信封包手抓包夹包软韩版潮","price":"889","sale":"18","review":"5"},
                {"name":"宾度 男士手包真皮大容量手拿包牛皮个性潮男包手抓包软皮信封包","price":"322","sale":"35","review":"12"},
                {"name":"唯美诺新款男士手包男包真皮大容量小羊皮手拿包信封包软皮夹包潮","price":"523","sale":"29","review":"3"},
                ]
  }
})
</script>

自定义指令

下面我们使用了directive定义了一个指令:xart,其中el是使用了该指令的元素,它会执行我们指令的内容。

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<div id="div1">
     
    <div v-xart> 好好学习,天天向上 </div>
     
</div>
 
<script>
 
Vue.directive('xart', function (el) {
    el.innerHTML = el.innerHTML + ' ( x-art ) '
    el.style.color = 'pink'
})
 
new Vue({
  el: '#div1'
})
</script>

带参数的自定义指令

v-xart="{color:'red',text:'best learning video'}"这是一条指令={ } 里面以键值对的方式提供了参数,在我们的函数中使用binding.value来获取。
binding.value.text获取到了best learning video这一字符串。

<script src="http://how2j.cn/study/vue.min.js"></script>
 
<div id="div1">
     
    <div v-xart="{color:'red',text:'best learning video'}"> 好好学习,天天向上 </div>
     
</div>
 
<script>
 
Vue.directive('xart', function (el,binding) {
    el.innerHTML = el.innerHTML + '( ' + binding.value.text + ' )'
    el.style.color = binding.value.color
})
 
new Vue({
  el: '#div1'
})
</script>

Vue路由

这里我们需要引入一个新的js:<script src="http://how2j.cn/study/vue-router.min.js"></script>

<script src="http://how2j.cn/study/vue.min.js"></script>
<script src="http://how2j.cn/study/vue-router.min.js"></script>
<head>
    <style>
     
    a{
      text-decoration: none;
    }
    a.router-link-active{
    /*   color:blue; */
      background-color: lightGray;
    }
    div.menu{
        border:1px solid gray;
        float:left;
    }
    div.menu a{
        display:block;
    }
     
    div.workingRoom{
        margin-left:100px;
    }
     
    div#app{
        width:500px;
        padding:10px;
        margin:10px auto;
    }
    </style>
</head>
<div id="app">
    <div class="menu">
        <!--
            router-link 相当于就是超链
            to 相当于就是 href
        -->
        <router-link to="/user">用户管理</router-link>
        <router-link to="/product">产品管理</router-link>
        <router-link to="/order">订单管理</router-link>
    </div>
     
    <div class="workingRoom">
        <!--
            点击上面的/user,那么/user 对应的内容就会显示在router-view 这里
         -->
         <router-view></router-view>   
    </div>
 
</div>
<script>
    /*
    * 申明三个模板( html 片段 )
    */
    var user = { template: '<p>用户管理页面的内容</p>' };
    var second = { template: '<p>产品管理页面的内容</p>' };
    var order = { template: '<p>订单管理页面的内容</p>' };
    /*
    * 定义路由
    */
    var routes = [
        { path: '/', redirect: '/user'}, // 这个表示会默认渲染 /user,没有这个就是空白
        { path: '/user', component: user },
        { path: '/product', component: second },
        { path: '/order', component: order }
    ];
    /*
    * 创建VueRouter实例
    */
    var router = new VueRouter({
        routes:routes
    });
    /*
    * 给vue对象绑定路由
    */
    new Vue({
        el:"#app",
        router
    })
 
</script>

实现的效果:
在这里插入图片描述

ajax请求

下面介绍一些Vue比较流行的ajax框架。
ajax使用指南:

  1. 原生一般不在项目中直接用
  2. jquery 不如4,5方便
  3. vue-resource 已经不再维护了,所以不推荐
  4. fetch.js 是 vue.js 官方推荐
  5. axios.js 是vue.js 官方推荐

fetch.js

一般Vue使用一些框架来实现ajax请求,其中fetch.js就是一个比较流行的框架。
准备相关的json数据:{"name":"gareen","hp":"355"}
下面就是一个简单的ajax获取json数据例子。

<script src="http://how2j.cn/study/fetch.min.js"></script>
  
<div id="hero">
  
</div>
  
<script>
var url = "http://how2j.cn/study/json.txt"
fetch(url).then(function(response) {
    response.json().then(function (jsonObject) {
        var jsonString = JSON.stringify(jsonObject)
        document.getElementById("hero").innerHTML = "通过fetch获取到的json数据:"+ jsonString;
    })
}).catch(function(err){
    console.log("Fetch错误:"+err);
})
  
</script>

axios.js

<script src="http://how2j.cn/study/axios.min.js"></script>
  
<div id="hero">
  
</div>
  
<script>
var url = "http://how2j.cn/study/json.txt"
    axios.get(url).then(function(response) {
        var jsonObject = response.data;
        var jsonString = JSON.stringify(jsonObject)
        document.getElementById("hero").innerHTML = "通过 axios 获取到的json数据:"+ jsonString;
    })
  
</script>

fetch.js 加载数据

<script src="http://how2j.cn/study/vue.min.js"></script>
<script src="http://how2j.cn/study/fetch.min.js"></script>
  
<head>
<style>
table tr td{
    border:1px solid gray;
}
table{
    border-collapse:collapse;
    width:300px;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
 
</head>
<div id="div1">
    
    <table align="center" >
        <tr class="firstLine">
            <td>name</td>
            <td>hp</td>
        </tr>
          
        <tr v-for="hero in heros">
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
        </tr>
          
    </table>
  
</div>
  
<script>
var url = "http://how2j.cn/study/jsons.txt";
new Vue({
    el:'#div1',
    data:{
        heros:[]
    },
    mounted:function(){ //mounted 表示这个 Vue 对象加载成功了
        self=this
        fetch(url).then(function(response) {
            response.json().then(function (jsonObject) {
                self.heros = jsonObject
            })
        }).catch(function(err){
            console.log("Fetch错误:"+err);
        })
    }
})
</script>

axios.js

<script src="http://how2j.cn/study/vue.min.js"></script>
<script src="http://how2j.cn/study/axios.min.js"></script>
  
<head>
<style>
table tr td{
    border:1px solid gray;
}
table{
    border-collapse:collapse;
    width:300px;
}
tr.firstLine{
    background-color: lightGray;
}
</style>
 
</head>
<div id="div1">
    
    <table align="center" >
        <tr class="firstLine">
            <td>name</td>
            <td>hp</td>
        </tr>
          
        <tr v-for="hero in heros">
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
        </tr>
          
    </table>
  
</div>
  
<script>
var url = "http://how2j.cn/study/jsons.txt";
new Vue({
    el:'#div1',
    data:{
        heros:[]
    },
    mounted:function(){ //mounted 表示这个 Vue 对象加载成功了
        var self = this
        axios.get(url).then(function(response) {
            self.heros= response.data; //此时还是字符串
            self.heros = eval("("+self.heros+")");  //字符串转换为数组对象
        })     
    }
})
</script>

CRUD 实现 Vue

首先,列举出所有属性的表格、并添加编辑、删除按钮。

<html>
<head>
    <script src="http://how2j.cn/study/js/jquery/2.0.0/jquery.min.js"></script>
    <script src="http://how2j.cn/study/vue.min.js"></script>
    <style type="text/css">
        td{
            border:1px solid gray;
        }
          
        table{
            border-collapse:collapse;
        }
      
        div#app{
            margin:20px auto;
            width:400px;
            padding:20px;
        }      
    </style>
</head>
  
<body>
    <div id="app">
            <table id="heroListTable" >
                <thead>
                    <tr>
                        <th>英雄名称</th>
                        <th>血量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="hero in heros ">
                        <td>{{hero.name}}</td>
                        <td>{{hero.hp}}</td>
                        <td>
                            <a href="#nowhere" @click="edit(hero)">编辑</a>
                            <a href="#nowhere" @click="deleteHero(hero.id)">删除</a>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            英雄名称:
                            <input type="text"    v-model="hero4Add.name" />
                            <br>
                            血量:
                            <input type="number"    v-model="hero4Add.hp" />
                            <br>
                            <button type="button"  v-on:click="add">增加</button> 
                         </td>                  
                    </tr>
                </tbody>
            </table>
              
            <div id="div4Update">
              
                            英雄名称:
                            <input type="text"    v-model="hero4Update.name" />
                            <br>
                            血量:
                            <input type="number"    v-model="hero4Update.hp" />                       
                            <input type="hidden"    v-model="hero4Update.id" />                       
                            <br>
                            <button type="button"  v-on:click="update">修改</button>                
                            <button type="button"  v-on:click="cancel">取消</button>                
              
            </div>
    </div>
  
    <script type="text/javascript">
        //修改区域隐藏起来先
        $("#div4Update").hide();
  
        //Model
        var data = {
            heros: [
            { id: 1, name: '盖伦', hp: 318},
            { id: 2, name: '提莫', hp: 320},
            { id: 3, name: '安妮', hp: 419},
            { id: 4, name: '死歌', hp: 325},
            { id: 5, name: '米波', hp: 422},
            ],
            hero4Add: { id: 0, name: '', hp: '0'},
            hero4Update: { id: 0, name: '', hp: '0'}
        };
          
        //用于记录最大id值
        var maxId = 5;
        //计算最大值
        for (var i=0;i<data.heros.length;i++){
            if (data.heros[i].id > maxId)
                maxId=  this.heros[i].id;
        }      
          
    //ViewModel
    var vue = new Vue({
        el: '#app',
        data: data,
        methods: {
            add: function (event) {
                //获取最大id
                maxId++;
                //赋予新id
                this.hero4Add.id = maxId;
                if(this.hero4Add.name.length==0)
                    this.hero4Add.name = "Hero#"+this.hero4Add.id;
                //把对象加入到数组
                this.heros.push(this.hero4Add);
                //让 hero4Add 指向新的对象
                this.hero4Add = { id: 0, name: '', hp: '0'}
            },
            deleteHero: function (id) {
                console.log("id"+id);
                for (var i=0;i<this.heros.length;i++){
                    if (this.heros[i].id == id) {
                        this.heros.splice(i, 1);
                        break;
                    }
                }
            },
            edit: function (hero) {
                $("#heroListTable").hide();
                $("#div4Update").show();
                this.hero4Update = hero;
            },
            update:function(){
                //因为v-model,已经同步修改了,所以只需要进行恢复显示就行了
                $("#heroListTable").show();
                $("#div4Update").hide();          
            },
            cancel:function(){
                //其实就是恢复显示
                $("#heroListTable").show();
                $("#div4Update").hide();
            }
        }
    });
    </script>
<div style="height:300px"></div>
</body>
</html>

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值