学vue.js笔记

一、vuj的简介

1、vue.js是一套构建界面的渐进式框架

2、关注图层,自底向上增量开发


二、安装

1、官网下载js

2、直接引用(最简单方便的使用)
Staticfile CDN(国内) : https://cdn.staticfile.org/vue/2.2.2/vue.min.js

unpkghttps://unpkg.com/vue/dist/vue.js, 会保持和 npm 发布的最新的版本一致。

cdnjs : https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js

3、npm方法

用npm下载vue


npm install vue

(这个方法还不太会!!!)

4、命令行工具(太难了没看懂可以照着敲)


# 全局安装 vue-cli

$ cnpm install --global vue-cli

# 创建一个基于 webpack 模板的新项目

$ vue init webpack my-project

# 这里需要进行一些配置,默认回车即可

This will install Vue 2.x version of the template.

For Vue 1.x use: vue init webpack

进入项目,安装并运行:


$ cd my-project

$ cnpm install

$ cnpm run dev

DONE  Compiled successfully in 4388ms> 

Listening at http://localhost:8080

之后可以输入http://localhost:8080进入主界面(还没试过所以没有图)


三、vuj基础

1、语法格式:


var vm = new Vue({

…………

})

2、vue对象里面有的东西:

(1)el:表明是对某区域改动

如:


<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>

    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

</head>

<body>

<div id="app">

    <div v-html="message"></div>

</div>

<script>

    new Vue({

        el: '#app',

        data: {

            message: '<h1>菜鸟教程</h1>'

        }

    })

</script>

</body>

</html>

表明是对id为“app”的div块做变动

(2)data:定义属性

(3)methods:定义方法

(4)computed:计算属性:处理复杂逻辑

(5)watch:创建监听

(6)。。。还没学到后续补充

3、vue实例还提供实例方法,有前缀$


四、模板语法

1、插值

(1)文本:
在html中用{{ }}来显示属性值,vue属性值改变也会使html视图发生相应的改变
(2)、Html
使用v-html指令输出html代码块

<div id="app">
    <div v-html="message"></div>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    message: '<h1>xxxx</h1>'
  }
})
</script>

此时输出的是:


image.png

(3)属性
v-bind指令:

<div id="app">
  <label for="r1">修改颜色</label><input type="checkbox" v-model="use" id="r1">
  <br><br>
  <div v-bind:class="{'class1': use}">
  </div>
</div>
    
<script>
new Vue({
    el: '#app',
  data:{
      use: false
  }
});
</script>

表示如果use的值为true则将div的class绑定为class1
(4)表达式

<div id="app">
    {{5+5}}<br>
    {{ ok ? 'YES' : 'NO' }}<br>
    {{ message.split('').reverse().join('') }}
    <div v-bind:id="'list-' + id">xxxx</div>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    ok: true,
    message: 'xxxx',
    id : 1
  }
})
</script>

2、指令

(1)参数
①v-bind绑定参数:

<pre><a v-bind:href="url">xxxx</a></pre>

这里的href是参数,v-bind将href和url的值绑定在一起
可以进行对v-bind的缩写

<a :href="url">xxxx</a>

②v-on

<a v-on:click="doSomething">

v-on绑定监听,表示点击之后该做点什么
可以对代码进行缩写:

<a @click="doSomething">  <!--这里编辑器中可能会标红但可以忽略不管-->

(2)修饰符

<form v-on:submit.prevent="onSubmit"></form>

表示提交调用event.preventDefault()

event.preventDefault() 方法阻止元素发生默认的行为。
例如:

  • 当点击提交按钮时阻止对表单的提交
  • 阻止以下 URL 的链接

3、用户输入

(1)用v-model进行双向绑定:

<div id="app">
    <p>{{ message }}</p>
    <input v-model="message">
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    message: 'xxxx'
  }
})
</script>

v-model 指令用来在 input、select、textarea、checkbox、radio 等表单控件元素上创建双向数据绑定,根据表单上的值,自动更新绑定的元素的值。

(2)按钮用v-on来绑定事件

<div id="app">
    <p>{{ message }}</p>
    <button v-on:click="reverseMessage">反转字符串</button>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})
</script>

[注]除methods外还可以使用computed来实现翻转字符串

<div id="app">
    <p>原字符串{{message}}</p>
    <p>反转后的字符串(computed):{{reversedString}}</p>
    <p>反转后的字符串(method):{{mReverseString()}}</p> <!-- method里的方法调用要括号 -->
</div>
</body>
<script>
    var vm =new Vue({
        el:'#app',
        data:{
            message:'hello'
        },
        computed:{reversedString:function()
        {
            return this.message.split('').reverse().join('')
        }},
        //是methods不是method,这里犯了一个错
        methods: {
            mReverseString:function()
            {
                    return this.message.split('').reverse().join('')
            }
        }
    })
</script>

计算属性computed基于依赖缓存,只有相关依赖发生改变时才会重新取值。而使用 methods,在重新渲染的时候,函数总会重新调用执行。(这里不太懂)使用 computed 性能会更好,但是如果不希望缓存就可以使用 methods 属性。

4、过滤器

格式如下:

<!-- 在两个大括号中 -->
{{ message | capitalize }}

<!-- 在 v-bind 指令中 -->
<div v-bind:id="rawId | formatId"></div>

{{ message | capitalize }}中前一个为参数,后一个为过滤的方法
如实例将首字母大写:

<div id="app">
  {{ message | capitalize }}
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    message: 'runoob'
  },
  filters: {
    capitalize: function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  }
})
</script>

过滤器可以串联(可有多个过滤器同时发挥作用){{ message | filterA | filterB }}
也可以带参数{{ message | filterA('arg1', arg2) }}

五、条件和循环

1、条件

使用v-if实现条件判断,这个比较简单,一个例子即可解释:

<div id="app">
    <div v-if="type === 'A'">
      A
    </div>
    <div v-else-if="type === 'B'">
      B
    </div>
    <div v-else-if="type === 'C'">
      C
    </div>
    <div v-else>
      Not A/B/C
    </div>
</div>
    
<script>
new Vue({
  el: '#app',
  data: {
    type: 'C'
  }
})
</script>

也可以使用v-show来判断是否现实:<h1 v-show="ok">Hello!</h1>

2、循环

循环使用v-for指令:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<ol id="app">
    <li v-for="site in sites">
        {{site.name}}
    </li>
</ol>
</body>
<script>
    new Vue(
            {
                el:"#app",
            data:{
                sites:[
                    {name:'data1'},
                    {name:'data2'},
                    {name:'data3'}
                ]

    }
            }
    )
</script>
</html>

也可以运用在<template>模板中:

div id="app">
    <ul>
        <template v-for="site in sites">
            <li>{{site.name}}</li>
            <li>…………</li>
        </template>
    </ul>
</div>

可以直接遍历一个对象:

<div id="app">
  <ul>
    <li v-for="value in object">
    {{ value }}
    </li>
  </ul>
</div>
 
<script>
new Vue({
  el: '#app',
  data: {
    object: {
      name: 'gino',
      url: 'http://www.baidu.com',
      slogan: 'hello world!'
    }
  }
})
</script>

还可以提供第二个参数为键名,第三个参数为索引:

<div id="app">
  <ul>
    <li v-for="(value, key, index) in object">
     {{ index }}. {{ key }} : {{ value }}
    </li>
  </ul>
</div

也可以迭代整数:

<div id="app">
  <ul>
    <li v-for="n in 10">
     {{ n }}
    </li>
  </ul>
</div>

六、计算属性和监听属性

1、计算属性:

在之前已经说明了一部分计算属性和methods的区别
这里写一个特殊的例子,computed默认只有getter,但也可以定义一个setter

var vm = new Vue({
  el: '#app',
  data: {
    name: 'Google',
    url: 'http://www.google.com'
  },
  computed: {
    site: {
      // getter
      get: function () {
        return this.name + ' ' + this.url
      },
      // setter
      set: function (newValue) {
        var names = newValue.split(' ')
        this.name = names[0]
        this.url = names[names.length - 1]
      }
    }
  }
})
// 调用 setter, vm.name 和 vm.url 也会被对应更新
vm.site = 'hello www.baidu.com';
document.write('name: ' + vm.name);
document.write('<br>');
document.write('url: ' + vm.url);

2、监听属性

这个属性主要是靠两个例子理解
一个是计数器:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
    <p>{{counter}}</p>
    <button @click="counter++">click</button>  <!--忽略这个错-->
</div>
</body>
<script>
    var vm = new Vue({
        el:'#app',
        data:{
            counter:1
        }
    })
    vm.$watch('counter',function(newCounter,oldCounter){
        alert("计数从"+oldCounter+'变为'+newCounter)
    })
</script>
</html>

vm.$watch()这个方法是一个实例方法,用$符号来做区别

另一个例子是千米和米的转换器:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="compute">
    千米:<input v-model="kilometers">
    米:<input v-model="meters">
</div>
<p id='demo'></p>
</body>
<script>
    var vm = new Vue({
        el:'#compute',
        data:{
            kilometers:0,
            meters:0
        },
        watch:{
            kilometers:function(val)//只有一个参数,那就是新值
            {
                this.kilometers = val
                this.meters = val * 1000
            },
            metes:function(val){
                this.meters = val
                this.kilometers = val/1000
            }
        }
    })
    vm.$watch('kilometers',function(newValue,oldValue){
        document.getElementById('demo').innerHTML = '原'+oldValue+'千米,现'+newValue+'千米'
    })
</script>
</html>

这个可以实现千米和米的自动转换,先创建了两个属性kilometersmeters,然后再在watch对象中创建两个方法kilometersmeterswatch 会实时监听数据变化并改变自身的值

七、样式绑定

1、最基本的样式绑定

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <title></title>
    <style>
        .class1{
            width: 50px;
            height: 60px;
            background-color: red;
        }
    </style>
</head>
<body>
<div :class="{class1:isClass}" id="app"></div>
</body>
<script>
    new Vue({
        el:'#app',
        data:{
            isClass:true
        }
    })
</script>
</html>

相当于<div class="active"></div>

2、多个样式绑定

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <style>
        .active {
            width: 100px;
            height: 100px;
            background: green;
        }
        .text-danger {
            background: red;
        }
    </style>
</head>
<body>
<div id="app">
    <div
         :class="{ active: isActive, 'text-danger': hasError }">
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            isActive: true,
            hasError: true
        }
    })
</script>
</body>
</html>

其中<div :class="{ active: isActive, text-danger: hasError }"></div>中的单引号不能缺!
这是相对于想要覆盖样式的情况来说的,即activetext-danger中都有background-color要想使代码正确就必须加上单引号。
如无冲突则可不加:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <style>
        .base{
            width: 50px;
            height: 50px;
        }
        .class1{
            background-color: red;
        }
        .class2{
            background-color: saddlebrown;
        }
    </style>
</head>
<body>
<div id="app" >
     <div v-bind:class="{class2:is2,class1:is1}"></div>
        </div>
</body>
<script>
    new Vue({
        el:'#app',
        data:{
            isClass1:true,
            isClass2:{
                YN :true,
                NY:'aaa'
            },
            is1:true,
            is2:true
       }
    })
</script>
</html>

3、还可以用对象和方法:

<style>
    .class1{
        width: 50px;
        height: 50px;
        background-color: red;
    }
    .class2{
        background-color: gray;
    }
</style>
<body>
<div id="app" :class="classObject"></div>
</body>
<script>
    new Vue({
        el:'#app',
        data:{
            classObject: {
                class1: true,
                'class2': true
            }
        }
    })
</script>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <style>
        .base{
            width: 50px;
            height: 50px;
        }
        .class1{
            background-color: red;
        }
        .class2{
            background-color: saddlebrown;
        }
    </style>
</head>
<body>
<div id="app" >
     <div v-bind:class="classObject"></div>
        </div>
</body>
<script>
    new Vue({
        el:'#app',
        data:{
            isClass1:true,
            isClass2:{
                YN :true,
                NY:'aaa'
            }
        },
        computed:{
            classObject:function(){
                return {
                  base:true,
                    class1:this.isClass1 && !this.isClass2.YN,
                    'class2':this.isClass2.YN && this.isClass2.NY == 'aaa'
                }
            }
        }
    })
</script>
</html>

4、数组

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<style>
.active {
    width: 100px;
    height: 100px;
    background: green;
}
.text-danger {
    background: red;
}
</style>
</head>
<body>
<div id="app">
    <div v-bind:class="[activeClass, errorClass]"></div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
</script>
</body>
</html>

就是直接把数组作为参数传,不难理解
还可以用表达式:<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
5、内联样式
就是把class改成style,不过可以用这个做动态样式
照搬代码:

<div id="app">  
    <div v-bind:style="{color: 'red', fontSize: size + 'px'}">可以动态调节</div> 
    <div v-bind:style="computedStyle">可以动态调节</div>
    <div v-bind:style="objectStyle"> 可以动态调节</div> 
    <div v-bind:style="methodStyle()"> 可以动态调节</div> 
    {{size}}   
    <button @click="++size">+</button> 
    <button @click="--size">-</button>
</div>

<script>
var app = new Vue({
    el: '#app',
    data: {
        size: 20,
        objectStyle: {
            color: 'green',
            fontSize: 20 + 'px' //this.size为undefined
        }
    },
    methods:{
       methodStyle: function(){
           return {color: 'green', fontSize: this.size + 'px'} //失效,颜色也不会改变
       } 
    },
    computed: {
       computedStyle: function(){
       return {color: 'red' , fontSize: this.size + 'px'} 
       }
    },
   watch: {
     size: function(){
       this.objectStyle.fontSize = this.size + 'px'
     }
   }
})
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,002评论 6 509
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,777评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,341评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,085评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,110评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,868评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,528评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,422评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,938评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,067评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,199评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,877评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,540评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,079评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,192评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,514评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,190评论 2 357

推荐阅读更多精彩内容

  • 主要还是自己看的,所有内容来自官方文档。 介绍 Vue.js 是什么 Vue (读音 /vjuː/,类似于 vie...
    Leonzai阅读 3,355评论 0 25
  • 一、了解Vue.js 1.1.1 Vue.js是什么? 简单小巧、渐进式、功能强大的技术栈 1.1.2 为什么学习...
    蔡华鹏阅读 3,329评论 0 3
  • 深入响应式 追踪变化: 把普通js对象传给Vue实例的data选项,Vue将使用Object.defineProp...
    冥冥2017阅读 4,874评论 6 16
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 2,216评论 0 6
  • 33、JS中的本地存储 把一些信息存储在当前浏览器指定域下的某一个地方(存储到物理硬盘中)1、不能跨浏览器传输:在...
    萌妹撒阅读 2,085评论 0 2