uni-app的项目结构,和微信小程序原生的项目结构有着不一致的区别。如果说开发过程中必须要使用原生代码,就需要把原生代码作为组件的方式在uni-app项目中引入使用。
具体步骤如下:
S1. 在根目录创建wxcomponents
S2. 创建完成之后,在文件夹里创建原生格式文件
S3. index.json
{
"component": true
}
S4. index.js
Component({
// 这个玩意应该是传递参数时使用,可在wxml中直接使用
properties: {
// 这里定义了 innerText 属性,属性值可以在组件使用时指定
innerText: {
type: String,
value: 'default value 3242432',
}
},
data: {
// 这里是一些组件内部数据
someData: {}
},
// 声明周期函数
ready(){
console.log('我执行了')
},
methods: {
// 页面中使用的方法
customMethod: function(){
console.log('我点击了页面中的文字')
}
}
})
S5. index.wxml
<view class="viewBox">
<span biudtap="customMethod">{{innerText}}</span>
</view>
S6. index.wxss
.map_container{
height: 300px;
width: 100%;
}
.map {
height: 100%;
width: 100%;
}
S7. uniapp pages.json 全局配置组件路径(文件单独配置不生效,所以用了全局引入)
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "TEST",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8",
"navigationStyle": "custom",
"usingComponents": {
"custom": "/wxcomponents/custom/index"
}
},
S8. uniapp 在页面里面使用即可
<template>
<view>
<u-navbar
title="地图demo"
:background="{ background: 'rgba(255, 255, 255, 0.82)' }"
:borderBottom="false"
title-color="#000"
></u-navbar>
<custom name="uni-app" :innerText="123"
></custom
>
<view>引入原生组件</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
customMethod() {
console.log("223455");
},
},
};
</script>
参考文档:
小程序自定义组件支持 | uni-app官网 (dcloud.net.cn)
微信小程序自定义组件,具体文档见 自定义组件 | 微信开放文档 (qq.com)