表单类组件封装&v-model简化代码
创建 工程:
H:\java_work\java_springboot\vue_study
ctrl按住不放 右键 悬着 powershell
H:\java_work\java_springboot\js_study\Vue2_3入门到实战-配套资料\01-随堂代码素材\day04\准备代码\11-封装表单类组件
vue --version
vue create v-fengzhuang-demo
cd v-fengzhuang-demo
npm run serve
App.vue
<template class="app">
<BaseSelect :cityId="selectId" @changeId="selectId = $event"> </BaseSelect>
</template>
<script>
import BaseSelect from "./components/BaseSelect.vue";
export default {
data() {
return {
selectId: "103",
};
},
components: {
BaseSelect,
},
};
</script>
<style>
</style>
components\BaseSelect.vue
<template>
<div>
<select :value="cityId" @change="handleChange">
<option value="101">北京</option>
<option value="102">上海</option>
<option value="103">武汉</option>
<option value="104">深圳</option>
<option value="105">广州</option>
</select>
</div>
</template>
<script>
export default {
props: {
cityId: String,
},
methods: {
handleChange(e) {
// console.log(e.target.value);
this.$emit("changeId", e.target.value);
},
},
};
</script>
<style>
</style>
App.vue
<template class="app">
<!-- <BaseSelect :value="selectId" @input="selectId = $event"> </BaseSelect> -->
<div>
<BaseSelect v-model="selectId"></BaseSelect>
<BaseSelect :value="selectId" @input="selectId = $event"> </BaseSelect>
</div>
</template>
<script>
import BaseSelect from "./components/BaseSelect.vue";
export default {
data() {
return {
selectId: "103",
};
},
components: {
BaseSelect,
},
};
</script>
<style>
</style>
components\BaseSelect.vue
<template>
<div>
<select :value="value" @change="handleChange">
<option value="101">北京</option>
<option value="102">上海</option>
<option value="103">武汉</option>
<option value="104">深圳</option>
<option value="105">广州</option>
</select>
</div>
</template>
<script>
export default {
props: {
value: String,
},
methods: {
handleChange(e) {
// console.log(e.target.value);
this.$emit("input", e.target.value);
},
},
};
</script>
<style>
</style>