“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情”
安装
全局安装 vue-cli (要求是@4)
npm i -g @vue/cli@4
创建并运行uni-app
uni-app项目创建项目,拉取模板
语法: $ vue create -p dcloudio/uni-preset-vue 项目名称
拉取失败,解决方案⬇:
一、首先,在下载模板地址下载dcloudio/uni-preset-vue
二、然后 把指令改为 $ vue create -p 工具项目路径 项目名
选择 默认模版
找到 项目中 src/manifest.json的 mp-weixin节点 填写appid
运行命令 运行微信小程序
npm run dev:mp-weixin
在微信开发者工具中 来导入项目即可
❗要导入的是项目下的 dist/dev/mp-weixin
开发uniapp的注意点
1. 不要直接在微信开发者工具中 修改代码
实际工作中,不能直接改编译好后的代码,要改就应该改 项目的源代码
2. 开发时,标签尽可能使用小程序的,而语法尽可能使用vue的
easycom 组件引入方式
在uniapp中 引入组件的方式 变为两个步骤
-
必须按照固定格式创建组件
/components/组件名称/组件名称.vue
-
❗在页面中直接使用组件
为什么要使用它
-
支持promise(原生小程序一些api不支持)
-
跨平台,一段代码 直接运行到不同的平台上 (web、小程序、手机app)
uview
在uniapp 引入uview
-
安装依赖
npm i uview-ui@1.8.4 sass -
在
src/main.js文件中 全局引入 js库import uView from "uview-ui"; Vue.use(uView); -
在 uni.scss 中 引入 uview 的 sass 主题库
@import "uview-ui/theme.scss"; -
在 App.vue 中 引入 uview 的 sass 主题库
<style lang="scss"> @import "uview-ui/index.scss"; </style> -
pages.json 中 配置 easycom
{ "easycom": { "^u-(.*)": "uview-ui/components/u-$1/u-$1.vue" }, // 此为本身已有的内容 "pages": [ // ...... ] } -
Cli模式额外配置 如果您是vue-cli模式的项目,还需要在项目根目录的vue.config.js文件中进行如下配置:
// vue.config.js,如没有此文件则手动创建 module.exports = { transpileDependencies: ['uview-ui'] } -
在 页面中 使用 uview的按钮
<u-button type="primary" icon="map" text="图标按钮"></u-button>
批量导入uview组件的方法
如,想批量导入以下组件:
- 下载 uview源码地址,在vscode打开
- 在vscode全局查找方法:
- 找到的样式和css复制到自己的项目即可
补充
uniapp注册组件和注册页面
组件
定义
<template>
<button>{{ '苹果' }}</button>
</template>
<script>
</script>
<style>
</style>
使用
组件的导入,注册还是使用 Vue 的写法
组件的导入,注册还是使用 Vue 的写法 components: { Goods }
<Goods/>
页面
定义pages/goods/goods.vue
在 pages.json的 pages节点 注册
{
"path": "pages/goods/goods",
"style": {
"navigationBarTitleText": "黑马商品选择"
}
}
uniapp的组件和API调用
组件跳转页面
<navigator url="/pages/demo/demo">跳转到demo页</navigator>
JS方式跳转页面
<button @tap="gotoPage">点击按钮跳转</button>
gotoPage() {
// API 要考虑平台兼容性,使用 uni 封装的 API
uni.navigateTo({
url: '/pages/demo/demo'
})
}
uniapp新增数据
this.list.unshift(this.str)
- ❗uniapp 中不要使用 this.setDate()
删除数据
this.list = this.list.filter(item => item != delVal)
父传子-子传父-类名绑定
子组件通过 props 接收
props: {
item: {
type: String
}
this.$emit() 触发父组件的自定义事件
子:
this.$emit('send', this.item)
父:
<Goods @send="sendFn">
sendFn(val) { this.activeGoods = val }(接收子组件传过来的数据)
:class 动态类名绑定
:class="{ active: activeGoods === item }