悠悠楠杉
Vue项目实用经验
开始vue项目
首先安装node
下载地址:https://nodejs.org/zh-cn/
然后安装vue-cli脚手架
npm install -g vue-cli
vue-cli项目
第一步创建名为 zhizun的项目
~~.....
$ vue init webpack zhizun
项目回答
Project name:项目名称
Project description:项目描述
Author:作者
Runtime-only:构建方式,分为独立构建和运行构建,默认选择 standalone
vue-router:是否安装路由
ESLint: ESLint规范,有标准的缩进、空格等规范 可以选 N
Set up unit tests: N
Setup e2e tests with Nightwatch: N
完成后,执行
进入到项目文件里
$ cd zhizun
本地服务器运行,出来一个测试地址
$ npm run dev
····································································
安装cnpm淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
安装 ui 框架
$ cnpm install element-ui -S
使用方式
在入口文件 main.js中引入
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(Element)
····································································
需要打包stylus
$ cnpm install stylus stylus-loader -S
打包css文件
$ cnpm install css-loader style-loader -S
需要打包scss
$ cnpm install node-sass sass-loader -S
需要打包less
$ cnpm install less less-loader -S
····································································
安装 axios
cnpm install axios -S
1、全局使用方式
使用方式,在入口文件main.js中添加
import axios from 'axios'
Vue.prototype.$axios = axios
操作写法:
this.$axios.get('/api/index.json')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
在 config/index.js 中添加
proxyTable: {
'/api': {
target: 'http://localhost:8080',
pathRewrite: {
'^/api': '/static/data'
}
}
}
在 .gitignore 文件中,再添加 【不被webpack打包】
static/data
yarn-error.log* static/data # Editor
2、局部使用方式
哪个页面需要就添加到哪里
import axios from 'axios'
····································································
组件如何使用
- 先写好一个如 header.vue的组件
- 在需要的页面中执行如下步骤
1、引入组件
import header from '@/pages/common/Header'
2、组件注册
data () {
},
components: {
header
}
3、组件渲染在页面,在页面的中写入
<header></header>
父子组件传值:
父组件
<home-header :lists="headerData"></home-header>
data () {
return {
headerData: []
}
}
子组件接受:
props: {
list: Array
}
或者是:
prop: ["list"]
传方法:
父组件
<home-header :open="handelClick()"></home-header>
methods: {
handelClick (可接受一个来自子组件的值) {
console.log("hahaha")
}
}
子组件:
<button @click="getData()"></button>
methods: {
getData () {
this.$emit("open",可传一个值到父组件)
}
}
最后的最后测试完成后打包上线
$ npm run build
生成一个dist文件,里面的文件+api文件 就可直接上传到服务器
····································································
如何运行vue项目
1、安装cnpm
npm install -g cnpm --registry=http://registry.npm.taobao.org
2、安装webpack
cnpm install webpack -g
3、安装vue-cli
cnpm install vue-cli -g
以上有安装过的,可以直接执行以下命令
4、cd /项目名称
cd zhizun
5、npm install
cnpm install
6、npm run dev
cnpm run dev
报错提示
npm ERR! missing script: dev
执行cnpm run serve
如果不行就输入vue init webpack初始化将package.json中丢失的修复,然后cnpm intall安装依赖,最后cnpm run dev即可!
npm ERR! path
将no such file 或者 directory,access中指明的文件路径中的node_modules删除,然后再重新cnpm intall
Module build failed:BrowserslistError:
删除.browserslistrc文件就好了
npm ERR! code ELIFECYCLE
cnpm cache clean --force
rm -rf node_modules //删除指定文件或文件夹
rm -rf package-lock.json
cnpm install
cnpm install 成功之后再次启动 cnpm start