教程.Vue的常见用法

篇幅较长,建议使用 导航 配合 ctrl+f 快速搜索所需内容

一、安装使用

通过npm,安装脚手架

npm install -g @vue/cli

进入ui界面

vue ui



二、基础语法

Vue2示例

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

<div id="app">
	{{msg}}
</div>

<script type="text/javascript">
	var app = new Vue({
		el: '#app',
		data: {
			msg: 'this is msg'
		}
	})
</script>


模板语法

插值 {{ xxx }}

文本

数据绑定最常见的形式就是文本插值

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

<div id="app">
	{{msg}}
</div>

<script type="text/javascript">
	var app = new Vue({
		el: '#app',
		data: {
			msg: 'this is msg'
		}
	})
</script>

JavaScript 表达式

对于所有的数据绑定,Vue.js 都提供了完全的 JavaScript 表达式支持。

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

<div id="app">
    <div>{{ number + 1 }}</div>
    <div>{{ ok ? 'YES' : 'NO' }}</div>
    <!-- 把一个字符串分割成字符串数组,颠倒其元素的顺序,把数组中的所有元素放入一个字符串 -->
    <div>{{ message.split('').reverse().join('') }}</div>
</div>

<script>
    const app = new Vue({
        el: '#app',
        data() {
            return {
                number: 1,
                ok: true,
                message: 'Hello Vue!'
            }
        }
    })
</script>

指令 v-xxx

指令是带有 v- 前缀的特殊属性。

记忆方法,可以参考 样式属性 style=“width: 100px”。

  • v-bind 用于绑定数据和元素属性,缩写为 :
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

<div class="app">
    <a v-bind:href="url">click me</a> //完整语法
    <a :href="url">click me</a> //缩写
</div>

<script>
    var app = new Vue({
        el: '.app',
        data: {
            url: "https://www.baidu.com",
        }
    });
</script>

此外还可以绑定id,class等属性。v-bind:id与id的区别在于,前者是可以动态变化的。

  • v-on 指令,它用于监听 DOM 事件,缩写为 @
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

<div class="app">
    <button v-on:click="show">click</button> //完整语法
    <button @click="show">click</button> //缩写
</div>

<script>
    var app = new Vue({
        el: '.app',
        data: {},
        methods: {
            show() {
                alert("ok");
            }
        }
    });
</script>
  • v-html 指令,用于更新元素的 innerHTML
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

<div class="app">
    <div v-html="text">click</div>          
</div>

<script>
    var app = new Vue({
        el: '.app',
        data: {
            text: '<b style="color:red">this is text style</b>'
        },
        methods: {}

    });
</script>

注意:

v-html="text"{{text}} 的区别在于,前者会转变html格式,相当于innerHTML;后者只是原封不动带过来数据,相当于innerText

  • v-for 指令, 用于循环
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

<div id="app">
	<div>
		<ul>
			<li v-for="(item,index) in object">
				<div :id="'nameId_'+index">{{item}}{{index}}</div>
			</li>
		</ul>
	</div>
</div>

<script>
	var app = new Vue({
		el: '#app',
		data() {
			return {
				object: {
					name: '菜鸟教程',
					url: 'http://www.runoob.com',
					slogan: '学的不仅是技术,!'
				}
			}
		}
	});
</script>


计算属性,方法和侦听

计算属性(缓存) - computed

对于任何复杂逻辑,都应当使用计算属性,computed

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

<div id="app">{{fullName}}</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            firstName: 'full',
            lastName: 'name'
        },
        computed: {
            fullName: function() {
                return this.firstName + ' ' + this.lastName
            }
        }
    })
</script>

方法 methods

注意:

计算属性与方法不同,前者依赖缓存,后者每次执行都会重新计算。

方法 methods可以实现同样的效果,只是在div中,改为 fullname()

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

<div id="app">{{fullName()}}</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            firstName: 'full',
            lastName: 'name'
        },
        methods: {
            fullName: function() {
                return this.firstName + ' ' + this.lastName
            }
        }
    })
</script>

侦听 watch

侦听 watch 属性适合做侦听数据变动的工作。

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

<div id="app">{{ fullName }}
    <input v-model="firstName" type="text" />
    <input v-model="lastName" type="text" />
</div>

<script>
    const app = new Vue({
        el: '#app',
        data: {
            firstName: 'full',
            lastName: 'name',
            fullName: 'full name'
        },
        watch: {
            firstName: function(val) {
                this.fullName = val + ' ' + this.lastName
            },
            lastName: function(val) {
                this.fullName = this.firstName + ' ' + val
            }
        }
    })
</script>


表单输入绑定 v-model

即是用 v-model,表单 input、textarea 及 select 元素上创建双向数据绑定。

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

<div id="app">
    <input v-model="msg" placeholder="edit me">
    <div>Message is: {{ msg }}</div>
</div>

<script>
    const app = new Vue({
        el: '#app',
        data: {
            msg: ""
        }
    })
</script>


组件 component

全局空间已存在变量,局部访问全局$a=“123”;function fun(){   global $a;   echo $a; }fun();​全局空间不存在这个变量,全部访问局部function fun(){   global $a;   $a=“123”;}fun();echo $a;php

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

<div id="app">
	<msg></msg>
</div>

<script>
	Vue.component('msg', {
		template: '<div>this is msg</div>'
	})

	const app = new Vue({
		el: '#app'
	})
</script>

局部组件。只允许在内部使用。

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

<div id="app">
	<msg></msg>
</div>

<script>
	const msg = {
		template: '<div>this is msg</div>'
	}

	const app = new Vue({
		el: '#app',
		components: {
			msg: msg
		}
	})
</script>

Prop

一个组件默认可以拥有任意数量的 prop,任何值都可以传递给任何 prop。

我们能够在组件实例中访问这个值,就像访问 data 中的值一样。

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

<div id="app">
    <msg info="info of msg"></msg>
</div>

<script>
    Vue.component('msg', {
        props: ['info'],
        template: '<div>this is {{info}}</div>'
    })
    const app = new Vue({
        el: '#app'
    })
</script>


渲染函数 render

渲染函数,即 render ,用于创建HTML模板。其中包含 返回值(VNode)和 参数(createElement)

createElement ,简写为 h 既是 render 的参数,也是函数,且有三个参数。如下:

  1. 返回值,虚拟节点 VNode

  2. 参数,可参照 <div class='node'>string</div>

    (1)HTML标签名【必需】,例如:div

    (2)属性【可选,可多个】,例如:class='node'

    (3)内容【可选,可多个】,例如:string

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

<div id="app"></div>

<script>
    const app = new Vue({
        el: '#app',
        render: (h) => {
            return h('div', {
                class: 'node'
            }, 'string1')
        }
    })
</script>


路由 Vue router

需要单独引入其依赖文件,例如CDN链接

JS部分书写思路, 从后往前写

配置components

配置routers( constRouter )

定义router( newRouter )

定义VueApp( newVueApp ), 并在VueApp中使用router

单页版如下

<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/vue-router/2.7.0/vue-router.min.js"></script>

<div id="app">
    <!-- router-link 路由导航 -->
    <router-link to='link1'>link1</router-link>
    <router-link to='link2'>link2</router-link>

    <!-- router-view 路由出口 -->
    <router-view></router-view>
</div>

<script>
    // template 定义组件
    const link1 = {
        template: '<div>this is link1</div>'
    }
    const link2 = {
        template: '<div>this is link2</div>'
    }

    // constVueRouter 定义路由
    const routes = [{
        path: '/link1',
        component: link1
    }, {
        path: '/link2',
        component: link2
    }]

    // newVueRouter 创建路由实例并传递配置
    const router = new VueRouter({
        routes
    })

    // newVue 创建,挂载并配置Vue实例
    const app = new Vue({
        el: '#app',
        router
    })
</script>


数据请求

以 get 方法为例

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

<script type="text/javascript">
    $(function() {
        axios.get('json_demo.json').then(res => console.log(res)).catch(err => console.log(err))
    })
</script>



三、进阶技术

插槽 slot 的用法

插槽就是子组件中的提供给父组件使用的一个占位符,用 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的标签。简单理解就是子组件中留下个“坑”,父组件可以使用指定内容来补“坑”。以下举例子帮助理解。

新建两个页面,如下

page_a.vue

<template>
	<div>
		<p>我是A组件</p>
		<B>这是B的插槽</B>
	</div>
</template>

<script>
	import B from '../page_b/page_b.vue'
	export default {
		name: 'A',
		components:{
			B
		}
	}
</script>

page_b.vue

<template>
	<div>
		<p>我是B组件</p>
		<slot></slot>
	</div>
</template>

<script>
	export default {
		name: 'B'
	}
</script>

表格及分页(axios)

需要安装:axios,element-ui

注意:

el-table -> el-table-column -> prop,这里需要设置好接口内response的对应

created(),可以 利用该函数直接运行方法

<script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.12/index.js"></script>

<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

<div id="app">
	<el-card class="box-card membersTab">
		<!-- 数据表格 -->
		<el-table
			:data="tableData.slice((pageSettings.currentPage-1)*pageSettings.PageSize,pageSettings.currentPage*pageSettings.PageSize)"
			stripe style="width: 100%">
			<el-table-column label="id" width="180">
				<template slot-scope="scope">
					<span style="margin-left: 10px">{{ scope.row.id }}</span>
				</template>
			</el-table-column>
			<el-table-column label="name" width="180">
				<template slot-scope="scope">
					<span style="margin-left: 10px">{{ scope.row.name }}</span>
				</template>
			</el-table-column>
			<el-table-column label="age" width="180">
				<template slot-scope="scope">
					<span style="margin-left: 10px">{{ scope.row.age }}</span>
				</template>
			</el-table-column>>
		</el-table>
		<div class="tabListPage">
			<el-pagination small @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="pageSettings.currentPage" :page-sizes="pageSettings.pageSizes"
				:page-size="pageSettings.PageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="pageSettings.totalCount">
			</el-pagination>
		</div>
	</el-card>
</div>

<script>
	const app = new Vue({
		el: '#app',
		data() {
			return {
				id: '',
				name: '',
				age: '',
				tableData: [],

				// 分页配置
				pageSettings: {
					// 分页配置
					// 默认显示第几页
					currentPage: 1,
					// 总条数,根据接口获取数据长度(注意:这里不能为空)
					totalCount: 1,
					// 个数选择器(可修改)
					pageSizes: [3, 5, 10, 20],
					// 默认每页显示的条数(可修改)
					PageSize: 10,
				},
			}
		},
		mounted() {
			this.getData()
		},
		methods: {
			// 查询
			getData() {
				let that = this;

				axios({
					method: 'get',
					url: 'http://localhost:8888/query'
				}).then(
					function (res) {
						that.tableData = res.data;
						console.log(that.tableData);

						// 分页条目总数
						that.pageSettings.totalCount = that.tableData.length
					}
				).catch(err => console.log(err)).catch(err => console.log(err))
			},

			// 分页
			// 每页显示的条数
			handleSizeChange(val) {
				// 改变每页显示的条数 
				this.pageSettings.PageSize = val
				// 注意:在改变每页显示的条数时,要将页码显示到第一页
				this.pageSettings.currentPage = 1
			},
			// 显示第几页
			handleCurrentChange(val) {
				// 改变默认的页数
				this.pageSettings.currentPage = val
			}
		}
	})
</script>

<style lang="">
	.membersTab {
		width: 600px;
		margin: 20px auto;
	}
</style>

使用ECharts框架

使用方法:

  1. npm install echarts --save

  2. 在vue项目中引入echarts,在 main.js 中添加下面两行代码

    import * as echarts from 'echarts';

    Vue.prototype.$echarts = echarts

    import echarts from ‘echarts’ 引入echarts后,不能全局使用echarts,所以通过Vue.prototype将echarts保存为全局变量。原则上$echarts可以为任意变量名。

  3. 在vue文件中写入下列代码,如果报错,可以尝试添加 import * as echarts from 'echarts';

    //在Echarts.vue文件中
    <template>
      <div class="Echarts">
        <div id="main" style="width: 600px;height: 400px;"></div>
      </div>
    </template>
     
    <script>
    export default {
      name: 'Echarts',
      methods: {
        myEcharts(){
          var myChart = this.$echarts.init(document.getElementById('main'));
          //配置图表
          var option = {
            title: {
              text: 'echarts入门示例',
            },
            tooltip: {},
            legend: {
              data: ['销量']
            },
            xAxis: {
              data: ['衬衫','羊毛衫','雪纺衫','裤子','高跟鞋','袜子']
            },
            yAxis: {},
            series: [{
              name: '销量',
              type: 'bar',
              data: [5,20,36,10,10,20]
            }]
          };
          myChart.setOption(option);
        }
      },
      mounted(){
        this.myEcharts();
      }
    }
    </script>
     
    <style>
     
    </style>
    



四、项目相关

以下所有内容默认使用HBuilder X作为编辑器。

该软件对Vue类项目支持性好,并且可以自动化的补全代码以及初始化生产相关页面。

初始化及运行

初始化项目

使用 vue-cli 脚手架创建程序,通过指令 npm i vue-cli -g 安装脚手架。

使用 vue init webpack vue_demo 指令安装vue项目。


运行项目

命令行窗口打开项目文件夹;执行 npm i,安装插件;再执行 npm run dev,运行项目。



引入框架

例如引入element-ui

  1. 安装框架。命令行窗口打开项目文件夹;执行 npm i element-ui -S,安装该框架。

  2. 引入框架。打开文件 main.js,写入内容如下

    import Vue from 'vue';
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    import App from './App.vue';
    
    Vue.use(ElementUI);
    
    new Vue({
      el: '#app',
      render: h => h(App)
    });
    

    即可

    例如在 App.vue 添加一个switch开关,代码如下

    <el-switch
      v-model="value"
      active-color="#13ce66"
      inactive-color="#ff4949">
    </el-switch>
    
    <script>
      export default {
        data() {
          return {
            value: true
          }
        }
      };
    </script>
    


新增页面(未完成)

可以使用hbuilder在 pages 文件夹右键新建页面,即可快速新建页面相关文件及代码

在项目管理器的 pages 上,右键单击,选择 新建页面,并填入名称后创建页面。

然后在 pages.json 中,找到 pages,此位置写入相关代码。

如果想要在底边导航栏处显示出来,需要在 pages.json 中,找到 tabBar > list,此位置写入相关代码。




五、第三方框架 - Vue

以element-ui为例。

直接引入其CDN链接,即可使用,完整代码如下

注意js文件的引入顺序,先vue.js,后ui框架.js

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<link rel="stylesheet" href="//unpkg.com/element-ui@2.15.8/lib/theme-chalk/index.css">
	<script src="//unpkg.com/vue@2/dist/vue.js"></script>
	<script src="//unpkg.com/element-ui@2.15.8/lib/index.js"></script>
</head>

<body>
	<div id="app">
		<template>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="date" label="日期" width="180">
				</el-table-column>
				<el-table-column prop="name" label="姓名" width="180">
				</el-table-column>
				<el-table-column prop="address" label="地址">
				</el-table-column>
			</el-table>
		</template>
	</div>

	<script>
		var app = new Vue({
			el: '#app',
			data: {
				tableData: [{
					date: '2016-05-02',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-04',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1517 弄'
				}, {
					date: '2016-05-01',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1519 弄'
				}, {
					date: '2016-05-03',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1516 弄'
				}]
			}
		})
	</script>
</body>

</html>



六、注意事项

data的两种写法

data对象写法

data: {
	msg: 'this is msg'
}

data()函数写法

data() {
	return {
		msg: 'msg'
	}
}

data()函数写法的优点:
不使用return这种方式的数据会在项目的全局可见,会造成变量污染
把data包裹成函数以后,变量只在当前组件中生效,不会影响其他组件


传参是一个对象

写法为

let imgData = {
	deviceGrade: 1,
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值