1、生命周期
Vue生命周期:一个Vue实例从创建到销毁的整个过程
生命周期四个阶段:创建、挂载、更新、销毁
1、创建阶段:响应式数据
2、挂载阶段:渲染模板
3、更新阶段:数据修改、更新视图(执行多次)
4、销毁阶段:销毁实例
* 生命周期函数(钩子函数)
Vue生命周期过程中,会自动执行一些函数,被称为生命周期钩子,让开发者可以在特定阶段运行自己的代码
每个阶段都有两个钩子函数,其中主要的为:beforeCreate、created、beforeMount、mounted
例如:
const app=new Vue({el:'#app',data:{num:100},methods:{add() {this.num++},de() {this.num--}},beforeCreate() {console.log('创建开始')},created() {console.log('创建结束')},beforeMount() {console.log('挂载开始')},Mounted() {console.log('挂载结束')}})
执行结果:
(代码中有个小错误,mounted函数不需要首字母大写,导致挂载结束的日志加载不出)
2、工程化开发&脚手架Vue CLI
开发Vue的两种方式:
1、核心包传统开发模式:基于html/css/js文件,直接引入核心包,开发Vue
2、工程化开发模式:基于构建工具(例如:webpack)的环境中开发Vue
基本介绍:
Vue CLI是Vue官方提供的一个全局命令工具
可以帮助我们快速创建一个开发Vue项目的标准化基础架子【集成了webpack配置】
好处:开箱即用,零配置,内置babel等工具,标准化
使用步骤:
1、全局安装(一次):yarn global add @vue/cli 或npm i @vue/cli -g
2、查看Vue版本:vue --version
3、创建项目架子:vue create project-name(项目名-不能用中文)
4、启动项目:yarn serve或npm run serve(找package.json)
* 脚手架目录文件介绍&项目运行流程
创建出来的包如下:
主要需要聚焦于index.html、main.js、APP.vue三个文件
其中app.vue文件用于进行编辑
* 组件化开发& 根组件
1、组件化:一个页面可以拆分成多个组件,每个组件都有着自己独立的结构、样式、行为。
好处:便于维护,利于复用,提升开发效率
组件分类:普通组件、根组件
2、根组件:整个应用最上层的组件,包裹所有普通小组件
APP.vue文件(单文件组件)的三个组成部分:结构(html)、行为(js)、样式(css)
1、语法高亮插件:vetur
2、三部分组成:
template:结构(有且只能一个根元素)
script:js逻辑
style:样式(可支持less,需要装包)
3、让组件支持less
style标签,lang="less"开启less功能
装包:yarn add less less-loader
例如:
<template><div @click="fn2" class="APP"><div @click.stop="fn1" class="box"></div></div>
</template><script>export default {methods:{fn1(){alert('创建了一个vue项目')},fn2() {alert('冒泡了')}}}
</script><style>
.APP {width: 400px;height: 400px;background-color: pink;
}.box {width: 200px;height: 200px;background-color: blue;
}
</style>
效果:
* 普通组件的注册使用
注册组件的两种方式:
1、局部注册:只能在注册的组件内使用
创建.vue文件(三个组成部分)、在使用的组件内导入并注册
2、全局注册:所有组件内都能使用
创建.vue文件(三个组成部分)、main.js中进行全局注册
使用:
当成html标签使用`<组件名> </组件名>`
注意:
组件名规范,大驼峰命名法
局部注册,例如:
<template><div class="App"><!-- 头部组件 --><XxHeader></XxHeader><!-- 主体组件 --><XxMain></XxMain><!-- 底部组件 --><XxFooter></XxFooter></div>
</template><script>
import XxHeader from'./components/XxHeader.vue'
import XxMain from './components/XxMain.vue'
import XxFooter from './components/XxFooter.vue'export default {components:{XxHeader,XxMain,XxFooter}
}
</script><style>
.App {width: 400px;height: 400px;margin: 0 auto;background-color: skyblue;padding-left: 50px;padding-top: 5px;padding-bottom: 5px;box-sizing: border-box;
}
</style>
省略其他组件的样式代码
效果为:
全局注册,例如,在以上代码的基础上添加一个按钮:
main.js代码:
import { createApp } from 'vue'
import App from './App.vue'
import XxButton from './components/XxButton.vue'createApp(App).component('XxButton',XxButton).mount('#app')
组件代码:
<template><button class="xx-button">通用</button>
</template><script>
export default {}
</script><style>
.xx-button {width: 50px;height: 20px;background-color: green;
}
</style>
<template><div class="xx-header">我是xx-header<XxButton></XxButton></div></template>
最终结果: