文档:
https://distpicker.pigjian.com/
功能:vue端加载省
.市
.区
.
流程:
1.终端vue项目下,输入命令
a. npm install v-distpicker --save
b. yarn add v-distpicker --save
上面两个二选一,我当时用a报错,选择的b指令;
2.引用插件
a.全局插件,写在main.js
里面
import VDistpicker from 'v-distpicker'
Vue.component('v-distpicker', VDistpicker)
b.单页面引用
import VDistpicker from 'v-distpicker'
export default {
components: { VDistpicker }
}
3.使用
<template>
<v-distpicker></v-distpicker>
<template>
<script>
import VDistpicker from 'v-distpicker'
export default {
components: { VDistpicker },
}
</script>
4.案例:
<div class="region-list">
<v-distpicker type="mobile" @selected="show_modal"></v-distpicker>
</div>
<script>
import VDistpicker from 'v-distpicker'
export default {
components: {VDistpicker},
data() {
return {
address: {},
show: false
}
},
//初始化
created() {
},
methods: {
is_show() {
this.show = true
},
show_modal(data) {
this.show = !this.show
this.address.pca = data.province.value + ' ' + data.city.value + ' ' + data.area.value
// console.log(this.address.pca)
},
storeAddress() {
const data = {
name: this.address.name,
tel: this.address.tel,
pca: this.address.pca,
detail: this.address.detail,
}
this.axios.post(`/api/address/store`, data).then((res) => {
this.$router.push({name: 'address_list'})
})
}
},
}
</script>
细节:
-
is_show
是调出省市县
的选择框,因为show
默认是false
,点击is_show
之后,变成true
,搭配标签内的v-if="show"
-
show_modal(data)
是点击之后,做了两件事,第一件
当省,市,县都选择之后,关闭选择框,第二件
是将选择的省,市,县的value
属性拼接
,然后赋值到this.address.pca
用于下面新增或者编辑的时候调用,data是提交的值
-
storeAddress
是点击保存,将需要保存的数据赋值到data里面.然后传给后端,后端拆分接收
public function store(Request $request)
{
$customer_id = auth('api')->user()->id;
//将接收来的对象转成数组
$pca = explode(" ", $request->pca);
Address::create([
'customer_id' => $customer_id,
'province' => $pca[0],
'city' => $pca[1],
'area' => $pca[2],
'tel' => $request->tel,
'detail' => $request->detail,
'name' => $request->name,
]);
}
4.编辑页面写法跟新增略有不同
a. 编辑页面多一个edit显示
init: function () {
let id = this.$route.params.id
this.axios.get(`/api/address/edit/${id}`)
.then((res) => {
this.address = res.data.address
this.address.pca = this.address.province + ' ' + this.address.city + ' ' + this.address.area
})
},
从列表页面传一个地址id
过来,编辑页面接收id
,获取edit页面,后端写法
路由:Route::get('edit/{id}', 'AddressController@edit');
控制器:
public function edit($id)
{
$address = Address::find($id);
return response()->json(compact('address'));
}
b. 编辑页面更新的时候,传参data里面要带id过去
后端路由:Route::put('update', 'AddressController@update');
控制器:
public function update(Request $request)
{
$pca = explode(" ", $request->pca);
Address::where('id', $request->id)->update([
'province' => $pca[0],
'city' => $pca[1],
'area' => $pca[2],
'tel' => $request->tel,
'detail' => $request->detail,
'name' => $request->name,
]);
}