通常把Vue的实例命名为vm。vm对象封装了对视图的所有操作,包括数据读写、事件绑定、DOM更新
vm的构造函数是Vue,按照ES6的说法,vm所属的类是Vue,其中options是new Vue的参数,一般称之为选项或者构造选项。只要把图中的五个问号掌握,就可以搞清vue2实例。
第一个问号
options:new Vue的参数 new Vue(options){}
option 具有五类属性分别是数据 DOM 生命周期钩子 资源 组合 。由于每一类的属性具有繁多,在此不一一列举。
详情请查看官方文档 Vue2
入门属性
el(挂载点)
el-挂载点(挂载html文件里面有类名的标签)。可以与mount替换
PS:必须是html文件里面的具有类名的标签
render: 渲染 且html里原本的标签会被覆盖
//新建App.vue(文件)
<template> //html(页面视图)
<div id="red">
{{ n }}
<button @click="add">+1</button>
</div>
</template>
<script> //数据操作
export default {
data() {
return {n: 0};
},
methods: {
add() {
this.n += 1;
}
}
};
</script>
<style scoped> /*CSS*/
#red {
color: red
}
</style>
import Vue from 'vue';
import App from './App';
Vue.config.productionTip = false;
new Vue({
el: '#app'
render:h=>h(App)
});
页面显示
另一种挂载方式(与mount替换):
new Vue({
render: h => h(App)
}).$mount('#app');
//相当于
const vm =new Vue({
render: h => h(App)
});
vm.$mount('#app');
data(实例内部数据)
支持对象和函数,优先使用函数(data数据有bug)
new Vue({
data:{n:0}
});
//相当于
new Vue({
data():{
return {n:0}
}
});
//相当于
new Vue({
data:function(){
return {n:0}
}
});
Vue2完整版的写法
直接在main.js中写
<template> <!--写html-->
<div id="red">
{{ n }}
</div>
</template>
<script> //对数据进行操作,js
export default {
data() {
return {n: 0}; //此处的n便是template的n
},
};
</script>
<style scoped> /*写CSS*/
#red {
color: red
}
</style>
methods(方法)
事件处理函数或者普通函数,可以代替filter属性
特性:只要页面渲染,便会重新执行一次
方法:实际就是一个函数,只不过放在对象里面,变成对象的属性,方便对象直接调用。(obj.add())
<template>
<div id="red">
{{ n }}
<button @click="add">+1</button> <!--点击触发add函数-->
<hr>
{{ filter() }}
</div>
</template>
<script>
export default {
data() {
return {n: 0};
},
methods: {
add() { //add()函数,返回n+1的数值。this.n便是data里面的n
return this.n += 1; //return{},{}里面有this的情况下,去掉{}
},
filter() {
console.log('filter执行了一次')
return this.array.filter(i => i % 2 === 0);
}
}
};
</script>
<style scoped>
#red {
color: red
}
</style>
components(组件)
Vue 完整版
使用Vue组件,注意大小写,创建的文件名小写,调用组件用大写有三种创建方式
创建组件1
- 创建Demo.vue文件(组件)
- 导入Demo组件
new Vue({components:{Frank:Demo}})。Frank就是另给Demo起一个名字。{Frank:Demo}直接改成{Demo:Demo},按照ES6标准可以简写成{Demo}- 在new Vue的template里面调用
<Frank/>
创建组件2
- 利用Vue的component属性创建
component(id,{内容})- 在new Vue的template调用
<Demo2/>
创建组件3
- 利用变量创建组件
new Vue({components:{Frank:x}})。Frank就是另给变量x(组件)起一个名字- 在new Vue的template调用
<Frank/>
生命周期钩子
(纯纯英文翻译)
created:出现在内存中,但是没有被挂载在页面上。
mounted:挂载在页面上。
updated:更新。
destroyed:消失。
PS:写在methods属性外面,用debugger进行调试
created() {
console.log('出现在内存中');
},
mounted() {
console.log('已经被挂载在页面中');
},
updated() {
console.log('已经更新了');
console.log(this.n);
},
destroyed() {
console.log('已经消失了')
}