Vue官方网站:https://cn.vuejs.org
下载vue.js
在html中引用,这里最好在head中引用,防止页面抖动。
下面为一些基础语法的代码,基本都有注释。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test Vue</title>
<script type="text/javascript" src="./vue.js"></script> <!--在head里面引入,防抖动 -->
</head>
<body>
<!-- 挂载点,模板,实例之间的关系 -->
<!-- Vue实例只会处理挂载点下面的内容,此处id=root的div为挂载点 -->
<!-- 在挂载点内部的内容都是模板内容 模板可以在vue实例里面的template编写 -->
<div id="root">
<h1>hello {{msg}}</h1>
<h1 v-text="number"></h1>
<!-- v-html会进行一次转义 也就是转成html格式 -->
<div v-html="content"></div>
<!-- v-on: 可简写为@ -->
<div v-on:click="handleCLick">{{content}}</div>
<!-- 属性绑定和双向数据绑定 -->
<!-- 使用模板指令以后,那么=以后的内容相当于js表达式 -->
<!-- 单向绑定 v-bind: 可简写为 : -->
<div v-bind:title="title">hello world</div>
<!-- v-model 双向绑定 -->
<input v-model="content"></input>
<div>{{content}}</div>
<!-- 计算属性与监听器 -->
姓:<input v-model="firstName"></input>
名:<input v-model="lastName"></input>
<div>{{fullName}}</div>
<div>{{count}}</div>
<!-- v-if v-show v-for-->
<!-- v-show 只是加一个display属性 v-if会创建/删除 -->
<div v-if="show">hhh我显示了</div>
<button @click="showandhide">toggle</button>
<ul>
<!-- :key 需要唯一 -->
<li v-for="(item, index) of list" :key="index">{{item}}</li>
</ul>
</div>
<script type="text/javascript">
// 创建Vue实例
new Vue({
// el表示Vue实例和哪一个dom节点绑定 挂载点
el: "#root" ,
// template: '<h1>hello {{msg}}</h1>',
// Vue实例里面的所有数据
data:{
msg:"hello world",
number:123,
content:"this ia a content",
title:"this is hello world",
firstName: '',
lastName: '',
count: 0,
show: true,
list: [1, 2, 3]
},
// 计算属性 使用上一次的缓存值
computed: {
fullName: function(){
return this.firstName + ' ' + this.lastName
}
},
// 监听器:监听某个数据或计算属性的变化,变化了就执行对应函数
watch:{
firstName: function(){
this.count ++
},
lastName: function(){
this.count ++
}
},
// 事件触发函数定义
methods:{
handleCLick: function(){
// 改变Vue实例里面的data数据 面向数据进行编程
this.content = "world"
},
showandhide: function(){
this.show = !this.show
}
}
})
</script>
</body>
</html>