39、WXS脚本(小程序独有的一套脚本语言)
(1)作用:结合WXML,可以构建出页面结构
(2)应用:在小程序中充当过滤器。(wxml无法调用在页面的.js中定义的函数,但是wxml中可以调用wxs中定义的函数)
(3)wxs与js的关系(wxs的语法类似于js)
1)wxs有自己的数据类型
Number、string、boolean、object、function、array、、date日期类型、regexp正则
2)wxs不支持类似于ES6及以上的语法形式
不支持:let、const、解构赋值、展开运算符、箭头函数、对象属性简写
支持:var定义变量、普通函数类似于ES5的语法
3)wxs遵循CommonJs规范
Module对象、require()函数、module.exports对象
(4)内嵌wxs脚本
Wxs代码可以写在wxml文件的wxs标签中,类似于js代码可以写在html文件的script标签中一样
1)wxs标签注意事项
①必须提供module属性,用来指定当前wxs的模块名称
②语法
已知:

(5)外联wxs脚本
Wxs代码还可以编写在以.wxs后缀结尾的文件内,就像js代码可以编写在以.js文件结尾的文件中一样
1)在wxml中引入外联的wxs脚本时的注意事项
①在wxml中引入外联的wxs脚本时,必须为<wxs>标签添加module(用来指定模块的名称)和src属性(用来指定要引入的脚本路径)(src必须是相对路径)
②语法:
已知:

新建.wxs结尾的文件

新建方法

导出方法

导入

使用

(6)wxs的特点(wxs和js是完全不同的两种语言)
1)与js不同
为了降低Wxs的学习成本,wxs语言在设计时借鉴了大量的js语法,但是,本质上,wxs和js是完全不同的两种语言
2)不能作为组件的事件回调
Wxs典型的应用场景就是"过滤器",经常配合Mustache语法(插值表达式)进行使用,但是,在wxs中定义的函数不能作为组件的事件回调函数(不能用bind:tap绑定其中的方法)
3)隔离性(wxs的运行环境和其他js代码是隔离的)
①wxs不能调用js中定义的函数
②wxs不能调用小程序提供的API
4)性能好
①在ios设备上,小程序内的WXS会比js代码快2~20倍
②在Android设备上,二者的运行效率无差异
40、自定义组件
(1)组件的创建(为保证目录结构的清晰,建议把不同的组件,存放在单独的目录中)
1)在根目录新建components文件夹

2)在components文件夹下,右键,点击"新建Component",新建test文件


(2)引用组件
1)分类
①局部引用(组件只能在当前被引用的页面内使用)(在页面的json文件中配置组件方式)


在其他页面无效

②全局引用(组件可以在小程序的每个页面中使用)(在app.json中配置引用组件的方式)



3)全局引用与局部引用的区别(从使用频率和范围来看)
①如果某组件在多个页面中经常用到,建议进行"全局引用"
②如果某个组件只在特定的页面中被用到,建议进行"局部引用"
(3)组件与页面的区别
1)组件的.json文件中需要声明"component":true属性

2)组件的.js文件中调用的是Component()函数

3)组件的事件处理函数需要定义到methods节点中

(4)组件样式隔离
1)默认情况下,自定义组件的样式支队当前组件生效,不会影响组件之间的UI结构,比如:组件与组件之间、组件与小程序之间、小程序与组件们之间
2)好处:
①防止外界样式影响组件内部的样式
②防止组件的样式破坏外界的样式
3)注意:
①app.wxss中的全局样式对组件无效(具体来讲,是对组件内的标签无效)



②只有class选择器会有样式隔离的效果,id选择器、属性选择器、标签选择器不受样式隔离的影响

(5)修改组件样式的隔离选项
默认情况下,自定义组件 的样式隔离性能防止组件内外样式互相干扰的问题,但是有时需要外界能够控制组件内部的样式,可以通过styleIsolation实现
1)styleIsolation的可选值
①isolated(表示启用样式隔离,在自定义组件内外,使用class指定的样式不会相互影响):默认值为是

②apply-shared(表示页面wxss样式将影响到自定义组件,但自定义组件不会影响到页面):默认值为否

③shared(表示页面wxss样式影响到自定义组件,定义组件也影响到页面):默认值为否


2)语法:
①在组件的.json中配置

②在组件的js文件中配置
