一、模板语法
(1)插值
1.text
v-text=“xxx”可以代替{{}},只能解析普通文本
2.v-once可以执行一次插值
3.v-html可以解析html代码
4.插值内部可以用js单个表达式
(2)指令
1. v-if=“boolean”判断真假是否显示
2. v-bind:绑定,缩写为:
3. v-on: 监听,缩写为@
4. 可以绑定动态参数或修饰符返回值
(3)列表渲染
1. v-for遍历数组
(4)表单绑定
v-model双向数据绑定
(5)其他
1 v-pre,直接写在标签上,不需要表达式,跳过这个元素和他的子元素的编译过程,用来跳过没有指令的节点加快编译
2 v-cloak 保持在元素上直到关联实例结束编译
二、生命周期
1.生命周期钩子,给了用户在不同阶段添加自己的代码的机会
2.钩子介绍
①beforeCreate,函数类型,在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用
②created,函数类型,在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),property 和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el
property 目前尚不可用
③beforeMount,函数类型,在挂载开始之前被调用,render函数首次被调用,但是在服务器端渲染期间不被调用
④mounted,函数类型,实例被挂载之后调用
⑤beforeUpdate,函数类型,数据更新时调用
⑥updated,函数类型
⑦BeforeDestroy,可以调用函数但是一般不用,处理一些关闭定时器等等
⑧destroy
三、组件
1非单文件组件:一个文件中包含n个组件(a.html包含好多)
不需要写el配置项,最终所有组件都被vm管理,由其决定服务于哪个
data必须是函数
局部注册或者全局注册
2单文件组件:一个文件中只包含一个组件(a.vue)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!-- 引入vue-->
<script type="text/javascript" src="../../js/vue.js"></script>
</head>
<body>
<div id="root">
<!-- 编写组件标签-->
<hello></hello>
<school></school>
<hr>
<student></student>
</div>
<div id="root2">
<!-- 编写组件标签-->
<hr>
<hr>
<hello></hello>
</div>
</body>
<script>
//阻止vue在启动时生成生产提示
Vue.config.productionTip = false;
//创建school组件
const school = Vue.extend({
template:`
<div>
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="show">点我提示学校名</button>
</div>
`,
data(){
return{
schoolName:'尚硅谷',
address:'北京'
}
},
methods:{
show(){
alert(this.schoolName)
}
}
})
//创建student组件
const student = Vue.extend({
template:`
<div>
<h2>学生姓名:{{studentName}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
data(){
return{
studentName:'张三',
age:18
}
}
})
const hello=Vue.extend({
template:`
<div>
<h2>你好{{name}}</h2>
</div>
`,
data(){
return{
name:'tom'
}
}
})
Vue.component('hello',hello)//全局注册组件
//注册组件
new Vue({
el:'#root',
components:{
school,
student
},
})
new Vue({
el:'#root2',
})
</script>
</html>
子组件放在父组件之前
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!-- 引入vue-->
<script type="text/javascript" src="../../js/vue.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
<script>
//阻止vue在启动时生成生产提示
Vue.config.productionTip = false;
//定义student子组件
const student = Vue.extend({
name:"student",
template:`
<div>
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
data(){
return{
name:'张三',
age:18
}
}
})
//定义school父组件
const school = Vue.extend({
name:"school",
template:`
<div>
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{address}}</h2>
<student></student>
</div>
`,
data(){
return{
schoolName:'尚硅谷',
address:'北京'
}
},
components:{
student
}
})
//定义hello组件
const hello=Vue.extend({
template:`<h1>{{msg}}</h1>`,
data(){
return {
msg:"欢迎来到尚硅谷"
}
}
})
//定义app组件
const app=Vue.extend({
template:`
<div>
<hello></hello>
<school></school>
</div>
`,
components:{
school,
hello
}
})
new Vue({
template:`<app></app>`,
el:'#root',
//注册局部组件
components:{
app
}
})
</script>
</html>
单组件文件放到后面和脚手架一起