引言:
开始认识vue-cli,进行工程化开发把
从安装到设置路由,学习风格…
加油加油!
Vue-cli
认识Vue-cli
在cmd中输入如下代码
安装
1 2 3
| npm install -g @vue/cli # OR yarn global add @vue/cli
|
创建一个项目
1 2 3
| vue create my-project # OR vue ui
|
进入选项选择
选择Manually select features后我们手动配置
进入选择组件,以下就是常用组件
1 2 3 4 5 6 7 8 9 10
| ? Check the features needed for your project: (*) Babel ( ) TypeScript ( ) Progressive Web App (PWA) Support (*) Router 路由组件 (*) Vuex (*) CSS Pre-processors css预编译组件 >(*) Linter / Formatter ( ) Unit Testing ( ) E2E Testing
|
是否使用历史 -yes
是否使用ESlint -Airbnb
pick css? -SCSS
是否保存到将来的项目 -no
进入所建目录,运行
运行成功我们来看目录
- node_modules (依赖文件)
- src (放置源文件)关键
- public (公共资源)关键
- package.json (对整个项目的解释说明)关键
index.html内有挂载点,默认id为app
main.js创建了Vue实例,而且引入了两个东西
- router路由
- store这个是Vuex的引入,管理组件之间的状态
内部代码如下:
1 2 3 4 5
| new Vue({ router, store, render: h => h(App), }).$mount('#app');
|
Vue组件化思想
为什么要组件化?
实现了模块的复用,利于维护
可以高效的执行
降低单页面复杂难度
怎么拆分
300行原则
复用原则
业务复杂性原则
带来的问题用什么解决
组件状态管理 Vuex
多组件混合使用,业务复杂 vue-router
组件之间传参、消息、事件管理 props,emit/on,bus
风格指南
详情点击这里,Vue官方的风格指南
Vue-router 路由
怎么把一个组件拓展到路由内呢?
- 新建一个组件
Info.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div> 怎么设置路由 </div> </template>
<script> export default { name: '' }; </script>
<style scoped>
</style>
|
- 在src文件下的router.js内的routers里面添加这个组件的信息,并在开头记住引包
1
| import Info from './views/Info.vue';
|
1 2 3 4 5
| { path: '/', name: 'home', component: Home, },
|
- 打开App.vue文件,设置页面上的链接,设置
router-link
完成
Vuex
Vuex是什么
为vue.js开发的状态管理模式
组件状态集中管理
组件状态改变遵循统一的规则
怎么使用Vuex
src目录下的store.js
文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import Vue from 'vue'; import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({ state: { }, mutations: { }, actions: {
}, });
|
步骤:
- 在自建的组件Info.vue内添加以下内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <template> <div> 怎么使用Vuex <button @click="InfoAdd()">添加</button> </div> </template>
<script> import store from '@/store' export default { name: 'Info', store, methods: { InfoAdd() { console.log('add Event from info') } } }; </script>
<style scoped>
</style>
|
- 打开
store.js
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import Vue from 'vue'; import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({ state: { count: 0, }, mutations: { increase() { this.state.count += 1; }, }, actions: {}, });
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <div> 怎么使用Vuex <button @click="InfoAdd()">添加</button> </div> </template>
<script> import store from '@/store' export default { name: 'Info', store, methods: { InfoAdd() { console.log('add Event from info') store.commit('increase') //3. 使用 commit 方法,括号内参数是第二步的方法名称 } } }; </script> <style scoped> </style>
|
这样我们就完成了Vuex的使用,那么怎么给另一个页面传值呢
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <template> <div class="about"> <h1>This is an about page</h1> {{msg}} </div> </template>
<script> import store from '@/store' export default { name:'about', store, data(){ return{ msg: store.state.count } } } </script>
|