uniapp switch开关选择器

uniapp switch开关选择器

需要接口时,给开关赋默认值的方法

1. 先获取接口里面的数据
//执行加载数据方法
onLoad() {
	this.updata();
},
// 获取数据
updata(){
	this.$http.get({
		// 接口地址
		url:'&do=store_set&act=set_read&storeid=31'
	}).then(res=>{
		console.log('res',res)
		// res.data为数组,因为里面只有一条数据,所以直接
		// 把第一条数据拿出来就是门店信息对象,存入storeinfo变量中
		this.storeinfo=res.data[0];
	})
}, 
  1. return里面定义storeinfo变量接受参数
data() {
	return {
		storeinfo:{},
	}
},
3. 此时storeinfo里面已经有数据,所以在HTML代码里面直接使用。

Switch的checked直接和接口返回的数据值相比较

如果返回数据里面的变量值为1,那么checked值就为true,否则就为false

*注 wechat为接口里面的一条变量名

<view>
	<text>微信text>
	<switch :checked="storeinfo.wechat==1 ? 1:0" @change="SCwechat" />
view> 
4. 点击开关的时候给wechat重新赋值 @change事件
// 	开关点击事件
// 微信开关
SCwechat (e) {
	// 点击开关的时候看value值得变化
	console.log('开关选择器',e.target.value) 
	// 如果e.target.value==true的时候,就给storeinfo里面的变量赋值为1,否则为0
	if (e.target.value){
		this.storeinfo.wechat=1
	} else {
		this.storeinfo.wechat=0
	}
	console.log(this.storeinfo.wechat);
},
5. 把修改后的值提交到接口
// 服务器更新
this.$http.post({
	// 修改接口
	url:'&do=store_set&act=storesedit&storeid=31',
	// 左边data为接口数据,右侧为修改后的数据 let data = this.storeinfo;
	data:data,
}).then(res=>{

你可能感兴趣的:(uniapp,vue.js,javascript)