先说说组件的结构
最好单独放一个文件夹,有依赖的话装依赖
Sjld.vue 内容
<template id="sjld"> <label > <select v-model="selected" prop="selected" > <option v-for="option in sheng" :value="option.id" :label="option.name" :key="option.id"> {{option.name}} </option> </select> <select v-model="selecteds" prop="selecteds"> <option v-for="v in shi" :value="v.id" :label="v.name" :key="v.id"> {{v.name}} </option> </select> <select v-model="selectedss" prop="selectedss"> <option v-for="n in xian" :value="n.id" :label="n.name" :key="n.id"> {{n.name}} </option> </select> <button type="info" @click="tijiao">提交</button> </label> </template> <script> export default { data:function(){ return { shi:[], xian:[], selected:‘‘, selecteds:‘‘, selectedss:‘‘, } }, props:{ citys:Array, sheng:Array, }, watch:{ selected:function(val, old){ const self=this; if(val != old){ self.shi=[]; let upid = self.selected; let len = self.citys.length; for (var i = 0; i < len; i++) { if(self.citys[i].upid == upid){ self.shi.push(self.citys[i]) } }; } }, selecteds:function(val, old){ const self=this; if(val != old){ self.xian=[]; let upid = self.selecteds; let len = self.citys.length; for (var i = 0; i < len; i++) { if(self.citys[i].upid == upid){ self.xian.push(self.citys[i]) } }; } }, }, methods:{ getcitys(){ const self=this; self.citys=JSON.parse(localStorage.getItem(‘citys‘)) self.sheng=JSON.parse(localStorage.getItem(‘sheng‘)) }, tijiao(){ const self=this; let data={ sheng:self.selected, shi:self.selecteds, xian:self.selectedss, } self.$emit(‘change‘, data); //console.log(data) }, }, mounted(){ //this.getcitys(); }, computed: { } } </script>
解释一下:props 父级传给组件的数据 然后用 $emit(‘方法名‘,数据) 返回父级数据
index.js 内容
白色的是引入组件,红色的是全局安装,带下划线的是组件的名字,黄色的是导出组件,缺一不可
现在组件已经封装好了,怎么用?跟其他组件一样使用
打开 main.js 加上
import sjld from ‘./components/sjld/index.js‘
Vue.use(sjld);
然后在项目中任意处
<sjld :citys="citys" :sheng="sheng" @change="change"></sjld>
citys ,cheng 对应组件中 props
chang 对应组件中$emit的方法
时间: 2024-10-27 06:18:38