# 小程序代码构成
# vue 写法
目前小程序支持 vue 写法规范来开发小程序,不过与常规 vue 写法也有一些不同之处,以下将一一讲解。
vue 文件可以分为三类,主组件,页面,组件。
App vue 是小程序的主组件,所有页面都是在
App.vue
下进行切换的,是页面入口文件。但App.vue
本身不是页面,这里不能编写视图元素,也就是没有<template>
组件 vue 文件一般放在
components
文件夹下,主要封装一些公用的组件,有<template>
、<script>
、<style>
。页面 vue 文件是小程序页面的主要部分,有
<template>
、<script>
、<style>
,下面从小程序视角讲解三者的作用和写法。
# template
template
与以往写网页项目不同的是标签,此处不建议写 <div></div>
、<p></p>
、<span></span>
等等标签写法,转而使用小程序封装好的 <view></view>
、<text></text>
等组件写法
<template>
<view class="container">
<view class="userinfo">
<button bindtap="showMessage">点击按钮显示Message</button>
</view>
<view class="textinfo" v-if="isShowMessage">
<text class="text">{{ message }}</text>
</view>
</view>
</template>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
常用的标签替换如下:
div
改成view
span、font
改成text
a
改成navigator
img
改成image
input
仅仅是输入框。 原 html 规范中input
不仅是输入框,还有radio
、checkbox
、时间、日期、文件选择功能。在小程序规范中,input
仅仅是输入框。其他功能有单独的组件或API
form
、button
、label
、textarea
、canvas
、video
这些还在。iframe
改成web-view
ul、li
没有了,都用view
替代。audio
不再推荐使用,改成api
方式
# script
<script>
与以往写网页项目不同的是运行环境的不同,不能使用 window、document、navigator、location 等专用对象,所以这些对象所带来的作用 在这里都不能使用,
页面 vue 的生命周期规范也不同。可细看: 页面生命周期
<script>
export default {
data() {
return {
textvalue:"123",
buttontype:"primary"
};
},
onLoad() {
this.textvalue="456"//这里修改textvalue的值,其实123都来不及显示就变成了456
},
methods: {
changetextvalue() {
this.textvalue="789"//这里修改textvalue的值,页面自动刷新为789
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
去 dom
化,改用 mvvm
模式
通过 mvvm
的语法把一个变量绑定到标签上,我们称为数据绑定。使用 vue
的数据绑定方式解决 js
和 dom
界面交互的问题
- alert、confirm 改成
bz.showModal
- ajax 改成
bz.request
- cookie、session 没有了,localStorage 改成
bz.storage
API
# style
<style>
与以往写网页项目也有小部分不同
*
选择器不支持- 元素选择器里没有
body
,改为了page
- 如果想使用根据屏幕宽度自适应的单位,推荐使用
rpx
<style>
page{
}
</style>
1
2
3
4
5
2
3
4
5
# 标准小程序写法
常规小程序 DSL 分为:bzml
、bzss
、js
、json
标准文件结构。
该写法规范还在建设中