Vue学习笔记

Vue

vue在MVVM中充当ViemModel层,与jQuery不同的是,vue面向数据编程,jQuery面向DOM编程

Vue 常用知识点(模板语法、条件渲染、列表渲染)

vue init webpack [项目名] ----初始化项目

模板语法

<div>
    
</div>
<script>
    new Vue({
        el : '.bg', // 挂载点
    	template : '{{msg}}', //模板
        data : {
            msg : 'hello vue'
        },
    	methods:{ //存储方法,使用v-on:属性='submit'
    		submit : function(){},
    		方法名 : function(){}
		}
    })
</script>

  • html标签中使用 v-bind绑定标签内部属性,和data中的值相绑定,简洁写法:直接使用 ‘:’
<a v-bind:href="url">aa</a>
data中:{
	url : "****"
}
  • v-on绑定方法,简写 @。

  • v-model:数据和显示双向绑定,属性v-model=“data-value”

  • 监听器:watch,通常监听一个变量,用于异步场景

    new Vue({
                el : "#app",
                data : {
                    mag : "Hello"
                },
                //监听,当监听对象发生变化时,触发方法
                watch : {
                    msg : function(newVal, oldVal){
                    //监听msg,两个变量,新值、旧值
                    }
                },
                computed : {
                    
                }
            })
    
  • 计算属性:computed:计算属性,通常用于数据的联动;只要方法中任何一个变量发生变化,它都会更新;它和watch都只能监听本实例内的变量

    new Vue({
    	el : "#app",
    	data : {
    		mag : "Hello"
    	},
    	computed : {
    		msg1 : function () { 
    			return 'computed + ' + this.mag;
    		}
    	}
    }) 
    // 使用var *** = new Vue() 可以在chrome的console里通过***看到vue的属性
    

条件渲染

  • v-if, v-else-if, v-else = “判断语句”
  • v-show = “判断语句”
  • 区别是,v-show只是隐藏,实际存在;v-if条件不符合就不生成html元素

列表渲染

  • v-for=“(item, index) of list” index是item在list中的下标

Class与Style绑定

<div id='eg' v-for="item in list" //迭代器遍历list
	v-bind:style="styleDiv"// 与data中的styleDiv绑定
	// v-bind:class="{'class值','条件'}" 或 "['a','b','c']" 添加多个class值;二者可以混用
	v-bind:class="['class_1','class_2',{'class_3' : item.age > 21}]">
		{{item.name}}
		{{item.age}}
</div>
<script>
    new Vue({
            el : '#eg',
            data : {
                list : [{
                    name : 'aa',
                    age : 21
                },{
                    name : 'bb',
                    age : 22
                }],
                styleDiv : {//注意格式
                    color : 'green'
                }
            }
        });
</script>  

组件拆分

<div id="root">
        <div>
            <input type="text" v-model="inputValue" />// 双向绑定
            <button @click="handleSubmit">提交</button>
        </div>
        <ul>
            <!-- 将子组件放入父组件中 
                todo-item属于父组件,
                todo-item中v-for生成的内容属于子组件,因为内容是子组件的模板
            -->
            <todo-item
                v-for="(item, index) of list" 
                :property="item"				// 声明一个标签的属性,属性名自定义
                :index="index"
                :id="index"
                @delete="handleDelete"   //父组件监听delete事件,有响应时触发handleDelete方法
			>
            </todo-item>
        </ul>

    <script>
        // 定义一个"全局"组件,名字为todo-item
        // 直接在body中 <todo-item> </todo-item>使用
        Vue.component('todo-item', {
            // props关键字:接受的参数,用于向子组件传值
            props : ['property', 'index']// 这个模板是子组件的,所以事件也是触发子组件中的
            // 如果不声明接受参数,则无法识别property
            template: '<li> {{property}} </li>',
            methods : {
                handleClick : function(){
                    // 实现:点击<li>删除该记录
                    // 子组件需要被点击时,删除掉父组件list中的项
            
                    // 子组件和父组件通信:子组件发布事件-父组件订阅事件

                    // 该组件向外触发一个事件 :事件名是delete,传参为index
                    this.$emit('delete', this.index)
                }
            }
        })
        
        new Vue({
            el : "#root",
            // 调用局部组件
            components : {
                // 组件名    : 组件实例
                'todo-item' : TodoItem
            },
            data : {
                inputValue : 'hello',
                list : []
            },
            methods : {
                handleSubmit : function(){
                    this.list.push(this.inputValue)
                },
                // 父组件监听子组件发出的delete事件触发时,执行的handleDelete方法
                handleDelete : function (index) {
                    this.list.splice(index, 1)
                },
            }
        })
        
        // 局部组件的注册:需要在实例中使用
        var TodoItem = {
            props : ['property']// 组件模板
            template : '<li> {{property}} </li>'
        }
    </script>
</div>

vue的核心就是组件化页面,每个vue实例都代表一个组件,之后进行组件间的嵌套形成页面

组件加载时初始化方法

使用组件的方法:mounted----------一个Vue生命周期中的钩子

<script>
export default {
  name: 'Balance',
  data () {
    return {
      accountBalance: '',
      availableBalance: ''
    }
  },
  mounted () {
    // 页面加载时执行
    this.$api.get('/money', {}, response => {
      if (response.status >= 200 && response.status < 300) {
        const data = response.data.data
        this.accountBalance = data.AccountBalance
        this.availableBalance = data.AvailableBalance
      } else {
        alert('请求失败')
      }
    })
  }
}
</script>

Vue2.x 核心技术(vue-router、vuex)

vue-router-组件路由

Vue中,路由就是根据网址的不同,返回不同的内容给用户

  • router-view :显示的是当前路由地址所对应的内容;具体的地址映射关系写在router文件中

vuex-组件数据共享

npm install vuex --save

store组件,能够共享state状态值和mutation方法

Axios - 发生Ajax请求

npm install axios --save    安装axios

使用
import axios from 'axios'  

{
	axios.get('url')
}

axios封装配置

在项目中新建api/index.js文件,用以配置axios------来自[vue中使用axios]

api/index.js

import axios from 'axios';

let http = axios.create({
  // 设置了默认头部地址,会和config/index.js中的proxyTable设置的代理冲突
  baseURL: 'http://localhost:8080/',
  // 允许跨域请求,后台返回的response需要Access-Control-Allow-Credentials=true
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
  // 将JSON格式数据转为URL拼接的方式
  transformRequest: [function (data) {
    let newData = '';
    for (let k in data) {
      if (data.hasOwnProperty(k) === true) {
        newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
      }
    }
    return newData;
  }]
});

function apiAxios(method, url, params, response) {
  http({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
  }).then(function (res) {
    response(res);
  }).catch(function (err) {
    response(err);
  })
}

export default {
  get: function (url, params, response) {
    return apiAxios('GET', url, params, response)
  },
  post: function (url, params, response) {
    return apiAxios('POST', url, params, response)
  },
  put: function (url, params, response) {
    return apiAxios('PUT', url, params, response)
  },
  delete: function (url, params, response) {
    return apiAxios('DELETE', url, params, response)
  }
}

使用:在main.js中全局引入

import Api from './api/index.js';
Vue.prototype.$api = Api;

调用示例:

this.$api.post('user/login.do(地址)', {
    "参数名": "参数值"
}, response => {
     // response即为请求返回的response
     if (response.status >= 200 && response.status < 300) {
        console.log(response.data);\\请求成功,response为成功信息参数
     } else {
        console.log(response.message);\\请求失败,response为失败信息
     }
});

解决硬编码问题-引入常量库

在src目录下新建const.js文件,在该文件内声明常量并export

/**
 * 字符串常量库
 */
var TRADE_LOCATION = '营业厅'
var SAVE_MONEY_STATE = 1
var GET_MONEY_SATE = 2
var REQUEST_FAILURE = '请求失败,请稍后重试'

export default {
  SAVE_MONEY_STATE,
  GET_MONEY_SATE,
  TRADE_LOCATION,
  REQUEST_FAILURE
}

在main.js文件中导入并配置为VUE实例的原型(prototype,每个组件各自拥有一个实例,我没找到引入全局库的办法…)

import CONST from './assets/style/const' //文件位置

Vue.prototype.$CONST = CONST // 名称随意起

使用时:this.$CONST.***

环境配置

下载nvm node版本管理工具

where nvm
找到目录下的settings.txt
追加镜像
node_mirror: https://npm.taobao.org/mirrors/node/
npm_mirror: https://npm.taobao.org/mirrors/npm/

使用 nvm install latest 命令下载最新版本nodejs和npm(下载前需要卸载已存在的全局node版本,否则无法切换node版本)

nvm install <version> 下载node版本
nvm list 查看已下载的node版本
nvm use <version> 使用node版本

下载淘宝npm镜像:

npm install -g cnpm --registry=https://registry.npm.taobao.org
之后下载使用npm镜像 使用 cnpm install 命令

调试环境:

chrome + vue.js devtools插件

工程环境:vue-cli

npm/cnpm install -g vue-cli

前端库CDN

调试

  • Vue的chrome插件:vue.js devtools
  • console.log(),alert(), debugger(断点)
  • 给vue赋值一个实例
<select>
  <option v-for="(item, index) of currencyList" :key="index" 			  :value="item.exchangeRateId">
    {{item.currencyType}}
  </option>
</select>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值