微信小程序动态添加元素view

微信小程序是MVVM结构不存在动态添加元素
换个思路,models通过数组控制view元素显隐
方案:

文件wxml

	<view wx:for="{{info.details}}" wx:key="key" class="forItemBorder">
	 <view class="weui-cell weui-cell_input ">
	 <view class="weui-cell__hd">
	 <view class="weui-label rui-justify">
	 <text space="ensp">途 径 地</text>
	 </view>
	 </view>
	 <input class="weui-input" id="place-{{index}}" bindinput="setPlace" placeholder="请输入途径地" />
	 <input class="weui-input lcs" id="number-{{index}}" bindinput="setNumber" placeholder="里程数(km)" />
	 </view>
	</view>
	<!-- 添加-删除按钮 -->
	<view class="weui-cell" hidden="{{info.isPreDetail}}">
	 <button type='primary' bindtap='addItem' style='width:50%;'>增加途径地</button>
	 <button type='primary' bindtap='removeItem' style='width:50%;margin-left:5rpx;'>
	 删除途径地
	 </button>
	</view>

文件js

	/**
	 * Detail类 构造函数 
	 * @param {string} placeName 途径地
	 * @param {string} number 里程数
	 */
	function Detail(placeName, number) {
	 this.placeName = placeName;
	 this.number = number;
	}
	function Info() {
	 this.details = [];
	}
	Page({
	 data: {
	 info: {}
	 },
	 init: function () {
	 let that = this;
	 this.setData({
	  info: new Info(),
	 });
	 },
	 onLoad: function (options) {
	 this.init();
	 },
	 addItem: function (e) {
	 let info = this.data.info;
	 info.details.push(new Detail());
	 this.setData({
	  info: info
	 });
	 },
	 removeItem: function (e) {
	 let info = this.data.info;
	 info.details.pop();
	 this.setData({
	  info: info
	 });
	 },
	 
	})
	// 通过id属性来判断操作的是哪个Detail类
	setPlace: function (e) {
	 let index = parseInt(e.currentTarget.id.replace("place-", ""));
	 let place = e.detail.value;
	 let info = this.data.info;
	 info.details[index].placeName = place;
	 this.setData({
	  info: info
	 });
	 },
	setNumber: function (e) {
	 let index = parseInt(e.currentTarget.id.replace("number-", ""));
	 let number = e.detail.value;
	 let info = this.data.info;
	 info.details[index].number = number;
	 this.setData({
	  info: info
	 });
	 },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值